package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.common.PageResult;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxOrderList;
import com.adk.backend.entity.LxOrderStatus;
import com.adk.backend.entity.LxShipLog;
import com.adk.backend.mapper.ShipLogMapper;
import com.adk.backend.service.OrderService;
import com.adk.backend.service.OrderStatusService;
import com.adk.backend.util.ExcelUtil;
import com.adk.backend.util.LogUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 订单管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/orders")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private OrderStatusService orderStatusService;
    
    @Autowired
    private LogUtil logUtil;
    
    @Autowired
    private ExcelUtil excelUtil;
    
    @Autowired
    private ShipLogMapper shipLogMapper;
    
    @Autowired
    private com.adk.backend.mapper.AttrMapper attrMapper;
    
    @Autowired
    private com.adk.backend.util.FileUploadUtil fileUploadUtil;
    
    @Autowired
    private com.adk.backend.mapper.RecvLogsMapper recvLogsMapper;
    
    @Autowired
    private com.adk.backend.service.CustomerService customerService;
    
    @Autowired
    private com.adk.backend.util.BarcodeUtil barcodeUtil;
    
    // 特殊客户ID列表：这些客户需要根据add_uid过滤订单（个人管个人订单）
    private static final List<Long> MGT_ORDER_BY_USER_CID = java.util.Arrays.asList(203L, 95L, 346L);
    
    /**
     * 获取客户资料（用于客户自助修改）
     * 对应PHP: orders.php case 'profile'
     */
    @GetMapping("/profile")
    public Result<Map<String, Object>> getProfile(HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            Long customerId = (Long) request.getAttribute("customerId");
            
            Map<String, Object> result = customerService.getCustomerProfile(customerId, userId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取客户资料失败", e);
            return Result.error("获取客户资料失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存客户资料（用于客户自助修改）
     * 对应PHP: orders.php case 'saveprofile'
     * 支持表单提交和JSON提交两种方式
     */
    @PostMapping(value = "/saveprofile", consumes = {"multipart/form-data", "application/json"})
    public Result<Map<String, Object>> saveProfile(
            @RequestParam(value = "company_name", required = false) String companyName,
            @RequestParam(value = "cus_code", required = false) String cusCode,
            @RequestParam(value = "cus_short", required = false) String cusShort,
            @RequestParam(value = "contact_person", required = false) String contactPerson,
            @RequestParam(value = "contact_phone", required = false) String contactPhone,
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "wechat", required = false) String wechat,
            @RequestParam(value = "id_file", required = false) org.springframework.web.multipart.MultipartFile idFile,
            @RequestParam(value = "need_to_update", required = false) Integer needToUpdate,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            Long customerId = (Long) request.getAttribute("customerId");
            
            // 构建客户对象
            com.adk.backend.entity.LxCustomerList customer = new com.adk.backend.entity.LxCustomerList();
            
            // 如果有customerId，设置ID（更新现有客户）
            if (customerId != null && customerId > 0) {
                customer.setId(customerId);
            }
            
            // 设置客户信息
            customer.setCompanyName(companyName);
            customer.setCusCode(cusCode);
            customer.setCusShort(cusShort);
            customer.setContactPerson(contactPerson);
            customer.setContactPhone(contactPhone);
            customer.setEmail(email);
            customer.setWechat(wechat);
            
            // 判断是否是新客户（need_to_update==1且customerId为空）
            // PHP中：$_SESSION['need_to_update']==1 且 $id（customer_id）为空或0
            boolean isNewCustomer = (needToUpdate != null && needToUpdate == 1) && (customerId == null || customerId <= 0);
            
            // 保存客户资料
            Map<String, Object> result = customerService.saveCustomerProfile(customer, userId, idFile, isNewCustomer);
            
            if (Boolean.TRUE.equals(result.get("success"))) {
                // 如果创建了新客户，返回新的customerId供前端更新session
                return Result.success((String) result.get("message"), result);
            } else {
                return Result.error((String) result.get("message"));
            }
        } catch (Exception e) {
            log.error("保存客户资料失败", e);
            return Result.error("保存客户资料失败：" + e.getMessage());
        }
    }
    
    /**
     * 我的订单（客户自助查询 - 沙特空运）
     * 对应PHP: orders.php case 'my'
     */
    @GetMapping("/my")
    public Result<PageResult<LxOrderList>> getMyOrders(
            @RequestParam(required = false) String searchStartDate,
            @RequestParam(required = false) String searchEndDate,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer desAdd,
            @RequestParam(required = false) Integer whs,
            @RequestParam(required = false) String batchOrderNo,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            Long customerId = (Long) request.getAttribute("customerId");
            
            Map<String, Object> params = new HashMap<>();
            params.put("customerId", customerId);
            params.put("userId", userId);
            params.put("shipType", 1); // 沙特空运
            params.put("searchStartDate", searchStartDate);
            params.put("searchEndDate", searchEndDate);
            params.put("status", status);
            params.put("desAdd", desAdd);
            params.put("whs", whs);
            params.put("batchOrderNo", batchOrderNo);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<LxOrderList> result = orderService.getMyOrders(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取我的订单失败", e);
            return Result.error("获取我的订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 我的海运订单（客户自助查询 - 沙特海运）
     * 对应PHP: orders.php case 'mysea'
     */
    @GetMapping("/mysea")
    public Result<PageResult<LxOrderList>> getMySeaOrders(
            @RequestParam(required = false) String searchStartDate,
            @RequestParam(required = false) String searchEndDate,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer desAdd,
            @RequestParam(required = false) Integer whs,
            @RequestParam(required = false) String batchOrderNo,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            Long customerId = (Long) request.getAttribute("customerId");
            
            Map<String, Object> params = new HashMap<>();
            params.put("customerId", customerId);
            params.put("userId", userId);
            params.put("shipType", 2); // 沙特海运（拼柜和整柜）
            params.put("searchStartDate", searchStartDate);
            params.put("searchEndDate", searchEndDate);
            params.put("status", status);
            params.put("desAdd", desAdd);
            params.put("whs", whs);
            params.put("batchOrderNo", batchOrderNo);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<LxOrderList> result = orderService.getMyOrders(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取我的海运订单失败", e);
            return Result.error("获取我的海运订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 我的阿联酋空运订单（客户自助查询）
     * 对应PHP: orders.php case 'myuaeair'
     */
    @GetMapping("/myuaeair")
    public Result<PageResult<LxOrderList>> getMyUaeAirOrders(
            @RequestParam(required = false) String searchStartDate,
            @RequestParam(required = false) String searchEndDate,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer desAdd,
            @RequestParam(required = false) Integer whs,
            @RequestParam(required = false) Integer declareType,
            @RequestParam(required = false) String batchOrderNo,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            Long customerId = (Long) request.getAttribute("customerId");
            
            Map<String, Object> params = new HashMap<>();
            params.put("customerId", customerId);
            params.put("userId", userId);
            params.put("shipType", 3); // 阿联酋空运
            params.put("searchStartDate", searchStartDate);
            params.put("searchEndDate", searchEndDate);
            params.put("status", status);
            params.put("desAdd", desAdd);
            params.put("whs", whs);
            params.put("declareType", declareType);
            params.put("batchOrderNo", batchOrderNo);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<LxOrderList> result = orderService.getMyOrders(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取我的阿联酋空运订单失败", e);
            return Result.error("获取我的阿联酋空运订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 我的阿联酋海运订单（客户自助查询）
     * 对应PHP: orders.php case 'myuaesea'
     */
    @GetMapping("/myuaesea")
    public Result<PageResult<LxOrderList>> getMyUaeSeaOrders(
            @RequestParam(required = false) String searchStartDate,
            @RequestParam(required = false) String searchEndDate,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer desAdd,
            @RequestParam(required = false) Integer whs,
            @RequestParam(required = false) Integer declareType,
            @RequestParam(required = false) Integer declareStatus,
            @RequestParam(required = false) String batchOrderNo,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            Long customerId = (Long) request.getAttribute("customerId");
            
            Map<String, Object> params = new HashMap<>();
            params.put("customerId", customerId);
            params.put("userId", userId);
            params.put("shipType", 4); // 阿联酋海运
            params.put("searchStartDate", searchStartDate);
            params.put("searchEndDate", searchEndDate);
            params.put("status", status);
            params.put("desAdd", desAdd);
            params.put("whs", whs);
            params.put("declareType", declareType);
            params.put("declareStatus", declareStatus);
            params.put("batchOrderNo", batchOrderNo);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<LxOrderList> result = orderService.getMyOrders(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取我的阿联酋海运订单失败", e);
            return Result.error("获取我的阿联酋海运订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单文件列表
     * 对应PHP: orders.php case 'upload'
     */
    @GetMapping("/upload")
    public Result<Map<String, Object>> getOrderFiles(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getOrderFiles(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单文件列表失败", e);
            return Result.error("获取订单文件列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存订单文件
     * 对应PHP: orders.php case 'upload_save'
     */
    @PostMapping("/upload/save")
    public Result<String> saveOrderFiles(
            @RequestParam Long id,
            @RequestParam(value = "tk", required = false) org.springframework.web.multipart.MultipartFile[] tkFiles,
            @RequestParam(value = "fba", required = false) org.springframework.web.multipart.MultipartFile[] fbaFiles,
            @RequestParam(value = "asn", required = false) org.springframework.web.multipart.MultipartFile[] asnFiles,
            @RequestParam(value = "qt", required = false) org.springframework.web.multipart.MultipartFile[] qtFiles,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.saveOrderFiles(id, userId.intValue(), tkFiles, fbaFiles, asnFiles, qtFiles);
            if (success) {
                return Result.success("上传成功");
            } else {
                return Result.error("上传失败");
            }
        } catch (Exception e) {
            log.error("保存订单文件失败", e);
            return Result.error("保存订单文件失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取POD文件列表
     * 对应PHP: orders.php case 'uploadpod'
     */
    @GetMapping("/uploadpod")
    public Result<Map<String, Object>> getPodFiles(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getPodFiles(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取POD文件列表失败", e);
            return Result.error("获取POD文件列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存POD文件
     * 对应PHP: orders.php case 'uploadpod_save'
     */
    @PostMapping("/uploadpod/save")
    public Result<String> savePodFiles(
            @RequestParam Long id,
            @RequestParam(value = "pod", required = false) org.springframework.web.multipart.MultipartFile[] podFiles,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.savePodFiles(id, userId.intValue(), podFiles);
            if (success) {
                return Result.success("上传成功");
            } else {
                return Result.error("上传失败");
            }
        } catch (Exception e) {
            log.error("保存POD文件失败", e);
            return Result.error("保存POD文件失败：" + e.getMessage());
        }
    }
    
    /**
     * 上传装箱单Excel并解析
     * 对应PHP: orders.php case 'upload_pl_save'
     */
    @PostMapping("/upload-pl/save")
    @RequiresPermission("edit")
    public Result<String> uploadPackingList(
            @RequestParam Long id,
            @RequestParam(value = "zxd", required = false) org.springframework.web.multipart.MultipartFile plFile,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            if (plFile == null || plFile.isEmpty()) {
                return Result.error("请选择要上传的Excel文件");
            }
            
            boolean success = orderService.uploadPackingList(id, userId.intValue(), plFile);
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("上传装箱单Excel失败", e);
            return Result.error("上传装箱单Excel失败：" + e.getMessage());
        }
    }
    
    /**
     * 上传报关资料
     * 对应PHP: orders.php case 'upload_declare'
     * 注意：PHP中upload_declare_save只是返回错误，实际功能未实现
     */
    @GetMapping("/upload-declare")
    @RequiresPermission("view")
    public Result<Map<String, Object>> getUploadDeclareInfo(@RequestParam Long id, HttpServletRequest request) {
        try {
            LxOrderList order = orderService.getById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("orderId", order.getId());
            result.put("orderNo", order.getOrderNo());
            
            // 查询报关资料文件（type=8，如果存在）
            QueryWrapper<com.adk.backend.entity.LxAttr> wrapper = new QueryWrapper<>();
            wrapper.eq("tb_name", "order_list");
            wrapper.eq("tb_id", id);
            wrapper.eq("type", 8);
            wrapper.orderByAsc("order_list", "id");
            List<com.adk.backend.entity.LxAttr> declareFiles = attrMapper.selectList(wrapper);
            
            List<Map<String, Object>> fileList = new ArrayList<>();
            for (com.adk.backend.entity.LxAttr attr : declareFiles) {
                Map<String, Object> fileInfo = new HashMap<>();
                fileInfo.put("id", attr.getId());
                fileInfo.put("fileName", attr.getAttrDesc());
                fileInfo.put("fileUrl", attr.getAttr());
                fileInfo.put("uploadTime", attr.getAddTime());
                fileList.add(fileInfo);
            }
            result.put("declareFiles", fileList);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取上传报关资料信息失败", e);
            return Result.error("获取上传报关资料信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存报关资料文件
     * 对应PHP: orders.php case 'upload_declare_save'
     * 注意：PHP中此功能未实现，这里提供基础实现
     */
    @PostMapping("/upload-declare/save")
    @RequiresPermission("edit")
    public Result<String> saveDeclareFiles(
            @RequestParam Long id,
            @RequestParam(value = "declare", required = false) org.springframework.web.multipart.MultipartFile[] declareFiles,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            if (declareFiles == null || declareFiles.length == 0) {
                return Result.error("请选择要上传的文件");
            }
            
            int timers = (int) (System.currentTimeMillis() / 1000);
            
            // 保存报关资料文件（type=8）
            for (int k = 0; k < declareFiles.length; k++) {
                org.springframework.web.multipart.MultipartFile file = declareFiles[k];
                if (file == null || file.isEmpty()) {
                    continue;
                }
                
                String originalFilename = file.getOriginalFilename();
                if (originalFilename == null || originalFilename.isEmpty()) {
                    continue;
                }
                
                // 获取文件扩展名
                String fileType = "";
                int lastDotIndex = originalFilename.lastIndexOf(".");
                if (lastDotIndex > 0 && lastDotIndex < originalFilename.length() - 1) {
                    fileType = originalFilename.substring(lastDotIndex + 1).toLowerCase();
                }
                
                // 验证文件类型（支持常见文档和图片格式）
                Set<String> allowedExtensions = new HashSet<>(java.util.Arrays.asList(
                    "jpg", "jpeg", "png", "pdf", "xls", "xlsx", "txt", "csv", "doc", "docx", "zip", "rar"
                ));
                
                if (!allowedExtensions.contains(fileType)) {
                    log.warn("文件类型不允许: {}", originalFilename);
                    continue;
                }
                
                // 创建上传目录
                java.io.File uploadDir = new java.io.File("uploads/declare");
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }
                
                // 生成文件名
                int tmpNums = k + 1;
                String str = String.valueOf(timers) + tmpNums;
                String fileName = userId + "-" + str + "." + fileType;
                
                // 保存文件
                java.io.File destFile = new java.io.File(uploadDir, fileName);
                file.transferTo(destFile);
                
                // 保存到数据库
                String attr = "/uploads/declare/" + fileName;
                com.adk.backend.entity.LxAttr lxAttr = new com.adk.backend.entity.LxAttr();
                lxAttr.setType(8); // 报关资料
                lxAttr.setTbName("order_list");
                lxAttr.setTbId(id);
                lxAttr.setAttr(attr);
                lxAttr.setAttrDesc(originalFilename);
                lxAttr.setOrderList(tmpNums);
                lxAttr.setAddTime(timers);
                attrMapper.insert(lxAttr);
            }
            
            return Result.success("上传成功");
        } catch (Exception e) {
            log.error("保存报关资料文件失败", e);
            return Result.error("保存报关资料文件失败：" + e.getMessage());
        }
    }
    
    /**
     * 查看装箱单
     * 对应PHP: orders.php case 'view_pl'
     */
    @GetMapping("/view-pl")
    @RequiresPermission("view")
    public Result<Map<String, Object>> getPackingList(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getPackingList(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取装箱单失败", e);
            return Result.error("获取装箱单失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除附件
     * 对应PHP: orders.php case 'del_attr'
     */
    @PostMapping("/attr/delete")
    @RequiresPermission("edit")
    public Result<String> deleteAttr(
            @RequestParam Long id,
            @RequestParam Long oid,
            @RequestParam(required = false, defaultValue = "0") Integer delType,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.deleteAttr(id, oid, userId.intValue());
            if (success) {
                if (delType != null && delType == 1) {
                    // AJAX请求，返回JSON
                    return Result.success("删掉了");
                } else {
                    return Result.success("删掉了");
                }
            } else {
                return Result.error("数据错误");
            }
        } catch (Exception e) {
            log.error("删除附件失败", e);
            return Result.error("删除附件失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取预约号码信息
     * 对应PHP: orders.php case 'booking_no'
     */
    @GetMapping("/booking-no")
    @RequiresPermission("view")
    public Result<Map<String, Object>> getBookingNo(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getBookingNo(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取预约号码信息失败", e);
            return Result.error("获取预约号码信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存预约号码
     * 对应PHP: orders.php case 'booking_no_save'
     */
    @PostMapping("/booking-no/save")
    @RequiresPermission("edit")
    public Result<String> saveBookingNo(
            @RequestParam Long id,
            @RequestParam(required = false) Long bookingNo,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.saveBookingNo(id, bookingNo, userId.intValue());
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("数据错误");
            }
        } catch (Exception e) {
            log.error("保存预约号码失败", e);
            return Result.error("保存预约号码失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取预约日期信息
     * 对应PHP: orders.php case 'booking_date'
     */
    @GetMapping("/booking-date")
    @RequiresPermission("view")
    public Result<Map<String, Object>> getBookingDate(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getBookingDate(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取预约日期信息失败", e);
            return Result.error("获取预约日期信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存预约日期
     * 对应PHP: orders.php case 'booking_date_save'
     */
    @PostMapping("/booking-date/save")
    @RequiresPermission("edit")
    public Result<String> saveBookingDate(
            @RequestParam Long id,
            @RequestParam(required = false) String bookingDate,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.saveBookingDate(id, bookingDate, userId.intValue());
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("数据错误");
            }
        } catch (Exception e) {
            log.error("保存预约日期失败", e);
            return Result.error("保存预约日期失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存头程单号
     * 对应PHP: orders.php case 'save_tx_no'
     */
    @PostMapping("/tx-no/save")
    @RequiresPermission("edit")
    public Result<String> saveTxNo(
            @RequestParam String ids,
            @RequestParam String txNo,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.saveTxNo(ids, txNo, userId.intValue());
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("保存头程单号失败", e);
            return Result.error("保存头程单号失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新订单信息（编辑箱号等）
     * 对应PHP: orders.php case 'edit_ctn_save'
     */
    @PostMapping("/edit-ctn/save")
    @RequiresPermission("edit")
    public Result<String> updateOrderInfo(
            @RequestParam Long id,
            @RequestParam(required = false) Integer editCtns,
            @RequestParam(required = false) Integer totalCtns,
            @RequestParam(required = false) java.math.BigDecimal totalGw,
            @RequestParam(required = false) java.math.BigDecimal totalVw,
            @RequestParam(required = false) String fbaNo,
            @RequestParam(required = false) Integer desAdd,
            @RequestParam(required = false) String desAddress,
            @RequestParam(required = false) String desPerson,
            @RequestParam(required = false) String desPhone,
            @RequestParam(required = false) String desAddressRemarks,
            @RequestParam(required = false) Integer declareType,
            @RequestParam(required = false) Integer isSensitive,
            @RequestParam(required = false) Integer t,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            Map<String, Object> params = new HashMap<>();
            if (editCtns != null) params.put("editCtns", editCtns);
            if (totalCtns != null) params.put("totalCtns", totalCtns);
            if (totalGw != null) params.put("totalGw", totalGw);
            if (totalVw != null) params.put("totalVw", totalVw);
            if (fbaNo != null) params.put("fbaNo", fbaNo);
            if (desAdd != null) params.put("desAdd", desAdd);
            if (desAddress != null) params.put("desAddress", desAddress);
            if (desPerson != null) params.put("desPerson", desPerson);
            if (desPhone != null) params.put("desPhone", desPhone);
            if (desAddressRemarks != null) params.put("desAddressRemarks", desAddressRemarks);
            if (declareType != null) params.put("declareType", declareType);
            if (isSensitive != null) params.put("isSensitive", isSensitive);
            if (t != null) params.put("t", t);
            
            boolean success = orderService.updateOrderInfo(id, params, userId.intValue());
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("数据错误");
            }
        } catch (Exception e) {
            log.error("更新订单信息失败", e);
            return Result.error("更新订单信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新订单品牌信息
     * 对应PHP: orders.php case 'save_brand'
     */
    @PostMapping("/brand/save")
    @RequiresPermission("edit")
    public Result<String> updateOrderBrand(
            @RequestParam Long id,
            @RequestParam(required = false) Integer isBrand,
            @RequestParam(required = false) String isBrandRemarks,
            @RequestParam(required = false) Integer isSensitive,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            Map<String, Object> params = new HashMap<>();
            if (isBrand != null) params.put("isBrand", isBrand);
            if (isBrandRemarks != null) params.put("isBrandRemarks", isBrandRemarks);
            if (isSensitive != null) params.put("isSensitive", isSensitive);
            
            boolean success = orderService.updateOrderBrand(id, params, userId.intValue());
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("数据错误");
            }
        } catch (Exception e) {
            log.error("更新订单品牌信息失败", e);
            return Result.error("更新订单品牌信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取签收日期信息
     * 对应PHP: orders.php case 'recv_date'
     */
    @GetMapping("/recv-date")
    @RequiresPermission("view")
    public Result<Map<String, Object>> getRecvDate(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getRecvDate(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取签收日期信息失败", e);
            return Result.error("获取签收日期信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存签收日期
     * 对应PHP: orders.php case 'recv_date_save'
     */
    @PostMapping("/recv-date/save")
    @RequiresPermission("edit")
    public Result<String> saveRecvDate(
            @RequestParam Long id,
            @RequestParam(required = false) String recvDate,
            @RequestParam(required = false) Integer recvType,
            @RequestParam(required = false) String recvNo,
            @RequestParam(required = false) Integer recvCtns,
            @RequestParam(required = false) String remarks,
            @RequestParam(value = "pod", required = false) org.springframework.web.multipart.MultipartFile[] podFiles,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.saveRecvDate(id, recvDate, recvType, recvNo, recvCtns, remarks, podFiles, userId.intValue());
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("数据错误");
            }
        } catch (Exception e) {
            log.error("保存签收日期失败", e);
            return Result.error("保存签收日期失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取单个订单的航班预约信息
     * 对应PHP: orders.php case 'booking_flight' (type=1)
     */
    @GetMapping("/booking-flight")
    @RequiresPermission("view")
    public Result<Map<String, Object>> getBookingFlightInfo(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getBookingFlightInfo(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取航班预约信息失败", e);
            return Result.error("获取航班预约信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取批量航班预约信息
     * 对应PHP: orders.php case 'booking_flight' (type=2,3,4)
     */
    @GetMapping("/booking-flight/batch")
    @RequiresPermission("view")
    public Result<Map<String, Object>> getBatchBookingFlightInfo(
            @RequestParam String ids,
            @RequestParam Integer type,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getBatchBookingFlightInfo(ids, type);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取批量航班预约信息失败", e);
            return Result.error("获取批量航班预约信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存航班预约（单个或批量）
     * 对应PHP: orders.php case 'booking_flight_save'
     */
    @PostMapping("/booking-flight/save")
    @RequiresPermission("edit")
    public Result<String> saveBookingFlight(
            @RequestParam(required = false) Long id,
            @RequestParam(required = false) String ids,
            @RequestParam(required = false) String slIds,
            @RequestParam(required = false) String flightDate,
            @RequestParam(required = false) String flightDateTime,
            @RequestParam(required = false) String flightDate2,
            @RequestParam(required = false) String flightDateTime2,
            @RequestParam(required = false) Integer flightType,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.saveBookingFlight(id, ids, slIds, flightDate, flightDateTime, 
                flightDate2, flightDateTime2, flightType, userId.intValue());
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("数据错误");
            }
        } catch (Exception e) {
            log.error("保存航班预约失败", e);
            return Result.error("保存航班预约失败：" + e.getMessage());
        }
    }
    
    /**
     * 编辑航班预约（单个或批量）
     * 对应PHP: orders.php case 'edit_booking_flight_save'
     */
    @PostMapping("/booking-flight/edit")
    @RequiresPermission("edit")
    public Result<String> editBookingFlight(
            @RequestParam(required = false) Long id,
            @RequestParam(required = false) String ids,
            @RequestParam(required = false) String slIds,
            @RequestParam(required = false) String flightDate,
            @RequestParam(required = false) String flightDate2,
            @RequestParam(required = false) Integer flightType,
            @RequestParam(required = false) String remarks,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.editBookingFlight(id, ids, slIds, flightDate, flightDate2, 
                flightType, remarks, userId.intValue());
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("数据错误");
            }
        } catch (Exception e) {
            log.error("编辑航班预约失败", e);
            return Result.error("编辑航班预约失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取ASN列表（分页）
     * 对应PHP: orders.php case 'ajax_get_asn'
     */
    @GetMapping("/asn/list")
    public Result<PageResult<Map<String, Object>>> getAsnList(
            @RequestParam(required = false) String shipDate,
            @RequestParam(required = false) String shipToWh,
            @RequestParam(required = false) Long cid,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("shipDate", shipDate);
            params.put("shipToWh", shipToWh);
            params.put("cid", cid);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<Map<String, Object>> result = orderService.getAsnList(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取ASN列表失败", e);
            return Result.error("获取ASN列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单的ASN列表（用于添加/编辑ASN）
     * 对应PHP: orders.php case 'asn_add'
     */
    @GetMapping("/asn/add")
    public Result<Map<String, Object>> getOrderAsnList(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getOrderAsnList(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单ASN列表失败", e);
            return Result.error("获取订单ASN列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存ASN
     * 对应PHP: orders.php case 'asn_save'
     */
    @PostMapping("/asn/save")
    public Result<String> saveAsn(
            @RequestParam Long id,
            @RequestParam(required = false) Map<String, Object> info,
            @RequestParam(value = "asn", required = false) org.springframework.web.multipart.MultipartFile[] asnFiles,
            @RequestParam(value = "sorting_details", required = false) org.springframework.web.multipart.MultipartFile sortingDetailsFile,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.saveAsn(id, userId.intValue(), info, asnFiles, sortingDetailsFile);
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (RuntimeException e) {
            log.error("保存ASN失败", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("保存ASN失败", e);
            return Result.error("保存ASN失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除ASN
     * 对应PHP: orders.php case 'asn_del'
     */
    @PostMapping("/asn/del")
    public Result<String> deleteAsn(@RequestParam Long id, @RequestParam(required = false) Long asnDel, HttpServletRequest request) {
        try {
            Long asnId = asnDel != null ? asnDel : id;
            boolean success = orderService.deleteAsn(asnId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除ASN失败", e);
            return Result.error("删除ASN失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单重量信息（用于编辑重量）
     * 对应PHP: orders.php case 'edit_weight'
     */
    @GetMapping("/edit_weight")
    public Result<Map<String, Object>> getOrderWeightInfo(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getOrderWeightInfo(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单重量信息失败", e);
            return Result.error("获取订单重量信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 查看订单重量信息（view_weight）
     * 对应PHP: orders.php case 'view_weight'
     */
    @GetMapping("/weight/view")
    @RequiresPermission("view_weight")
    public Result<Map<String, Object>> viewOrderWeight(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.viewOrderWeight(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查看订单重量失败", e);
            return Result.error("查看订单重量失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单下载文件列表（download）
     * 对应PHP: orders.php case 'download'
     */
    @GetMapping("/download")
    @RequiresPermission("download")
    public Result<Map<String, Object>> getOrderDownloadFiles(
            @RequestParam Long id,
            @RequestParam(defaultValue = "0") Integer t,
            HttpServletRequest request) {
        try {
            Integer userGroup = (Integer) request.getAttribute("userGroup");
            Map<String, Object> result = orderService.getOrderDownloadFiles(id, t, userGroup);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单下载文件列表失败", e);
            return Result.error("获取订单下载文件列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成打印标签（print_label）
     * 对应PHP: orders.php case 'print_label'
     */
    @GetMapping("/print_label")
    @RequiresPermission("print_label")
    public Result<Map<String, Object>> generatePrintLabel(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.generatePrintLabel(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("生成打印标签失败", e);
            return Result.error("生成打印标签失败：" + e.getMessage());
        }
    }
    
    /**
     * 标记订单已打印标签（print_label_without_confirm）
     * 对应PHP: orders.php case 'print_label_without_confirm'
     */
    @PostMapping("/print_label/mark")
    @RequiresPermission("print_label")
    public Result<Boolean> markOrderLabelPrinted(@RequestParam Long id, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean result = orderService.markOrderLabelPrinted(id, userId != null ? userId.intValue() : null);
            if (result) {
                return Result.success("Success.", true);
            } else {
                return Result.error("Data Error");
            }
        } catch (Exception e) {
            log.error("标记订单已打印标签失败", e);
            return Result.error("标记订单已打印标签失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取批量上传追踪信息（batch_upload_tracing）
     * 对应PHP: orders.php case 'batch_upload_tracing'
     */
    @GetMapping("/batch_upload_tracing")
    @RequiresPermission("batch_upload_tracing")
    public Result<Map<String, Object>> getBatchUploadTracingInfo(
            @RequestParam String ids,
            @RequestParam(defaultValue = "1") Integer t,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getBatchUploadTracingInfo(ids, t);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取批量上传追踪信息失败", e);
            return Result.error("获取批量上传追踪信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存批量上传追踪信息（batch_upload_tracing_save）
     * 对应PHP: orders.php case 'batch_upload_tracing_save'
     */
    @PostMapping("/batch_upload_tracing/save")
    @RequiresPermission("batch_upload_tracing")
    public Result<Boolean> saveBatchUploadTracing(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean result = orderService.saveBatchUploadTracing(params, userId != null ? userId.intValue() : null);
            if (result) {
                return Result.success("Success.", true);
            } else {
                return Result.error("Data Error");
            }
        } catch (Exception e) {
            log.error("保存批量上传追踪信息失败", e);
            return Result.error("保存批量上传追踪信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 预览计费重量
     * 对应PHP: orders.php case 'preview_shipweight'
     */
    @GetMapping("/preview_shipweight")
    public Result<Map<String, Object>> previewShipWeight(
            @RequestParam Long id,
            @RequestParam Integer type,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.previewShipWeight(id, type);
            return Result.success(result);
        } catch (Exception e) {
            log.error("预览计费重量失败", e);
            return Result.error("预览计费重量失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存重量编辑
     * 对应PHP: orders.php case 'edit_weight_save'
     */
    @PostMapping("/edit_weight/save")
    public Result<Map<String, Object>> saveWeightEdit(
            @RequestParam Long id,
            @RequestParam java.math.BigDecimal ship_weigth,
            @RequestParam Integer ship_weight_type,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.saveWeightEdit(id, userId.intValue(), ship_weigth, ship_weight_type);
            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 1);
                result.put("msg", "发送成功");
                return Result.success(result);
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 0);
                result.put("msg", "数据错误");
                return Result.error("操作失败");
            }
        } catch (RuntimeException e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("msg", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("保存重量编辑失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("msg", "保存失败");
            return Result.error("保存重量编辑失败：" + e.getMessage());
        }
    }
    
    /**
     * 确认重量
     * 对应PHP: orders.php case 'confirm_weight'
     */
    @PostMapping("/confirm_weight")
    public Result<Map<String, Object>> confirmWeight(@RequestParam Long id, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.confirmWeight(id, userId.intValue());
            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 1);
                result.put("msg", "已确认");
                return Result.success(result);
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 0);
                result.put("msg", "数据错误");
                return Result.error("确认失败");
            }
        } catch (Exception e) {
            log.error("确认重量失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("msg", "确认失败");
            return Result.error("确认重量失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单备注信息
     * 对应PHP: orders.php case 'remarks'
     */
    @GetMapping("/remarks")
    public Result<Map<String, Object>> getOrderRemarks(
            @RequestParam Long id,
            @RequestParam(defaultValue = "0") Integer t,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getOrderRemarks(id, t);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单备注信息失败", e);
            return Result.error("获取订单备注信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存订单备注
     * 对应PHP: orders.php case 'save_remarks'
     */
    @PostMapping("/save_remarks")
    public Result<String> saveOrderRemarks(
            @RequestParam Long id,
            @RequestParam(defaultValue = "0") Integer t,
            @RequestParam Map<String, String> info,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            String remarks = info.get("remarks");
            boolean success = orderService.saveOrderRemarks(id, t, userId.intValue(), remarks);
            if (success) {
                return Result.success("修改成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("保存订单备注失败", e);
            return Result.error("保存订单备注失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单费用信息
     * 对应PHP: orders.php case 'fee'
     */
    @GetMapping("/fee")
    public Result<Map<String, Object>> getOrderFeeInfo(@RequestParam Long id, HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getOrderFeeInfo(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单费用信息失败", e);
            return Result.error("获取订单费用信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取费用项（用于添加费用）
     * 对应PHP: orders.php case 'ajax_get_fee'
     */
    @GetMapping("/ajax_get_fee")
    public Result<Map<String, Object>> getFeeItem(
            @RequestParam Long id,
            @RequestParam Integer fee_type,
            @RequestParam Integer currency_id,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getFeeItem(id, fee_type, currency_id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取费用项失败", e);
            return Result.error("获取费用项失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存订单费用
     * 对应PHP: orders.php case 'fee_save'
     */
    @PostMapping("/fee/save")
    public Result<String> saveOrderFee(
            @RequestParam Long id,
            @RequestParam(required = false) BigDecimal[] price,
            @RequestParam(required = false) Integer[] currency_id,
            @RequestParam(required = false) Integer[] fee_type,
            @RequestParam(required = false) Long[] fee_id,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean success = orderService.saveOrderFee(id, userId.intValue(), price, currency_id, fee_type, fee_id);
            if (success) {
                return Result.success("操作成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (RuntimeException e) {
            log.error("保存订单费用失败", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("保存订单费用失败", e);
            return Result.error("保存订单费用失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除订单价格
     * 对应PHP: orders.php case 'del_price'
     */
    @PostMapping("/del_price")
    public Result<Map<String, Object>> deleteOrderPrice(@RequestParam Long id, HttpServletRequest request) {
        try {
            boolean success = orderService.deleteOrderPrice(id);
            Map<String, Object> result = new HashMap<>();
            if (success) {
                result.put("code", 1);
                result.put("msg", "删掉了");
                return Result.success(result);
            } else {
                result.put("code", 0);
                result.put("msg", "操作失败");
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除订单价格失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("msg", "操作失败");
            return Result.error("删除订单价格失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取沙特海运发货订单列表（seaf）
     * 对应PHP: orders.php case 'seaf'
     */
    @GetMapping("/seaf")
    public Result<PageResult<Map<String, Object>>> getSeafOrderList(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String batch_order_no,
            @RequestParam(required = false) Integer des_add,
            @RequestParam(required = false) Integer declare_type,
            @RequestParam(required = false) Integer declare_status,
            @RequestParam(required = false) String tx_date,
            @RequestParam(required = false) Long cid,
            @RequestParam(required = false) String ib_date,
            @RequestParam(required = false) Integer is_brand_remarks,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("status", status);
            params.put("batchOrderNo", batch_order_no);
            params.put("desAdd", des_add);
            params.put("declareType", declare_type);
            params.put("declareStatus", declare_status);
            params.put("txDate", tx_date);
            params.put("customerId", cid);
            params.put("ibDate", ib_date);
            params.put("isBrandRemarks", is_brand_remarks);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<Map<String, Object>> result = orderService.getSeafOrderList(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取沙特海运发货订单列表失败", e);
            return Result.error("获取订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取沙特空运发货订单列表（airf）
     * 对应PHP: orders.php case 'airf'
     */
    @GetMapping("/airf")
    public Result<PageResult<Map<String, Object>>> getAirfOrderList(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer des_add,
            @RequestParam(required = false) Integer declare_type,
            @RequestParam(required = false) Integer whs,
            @RequestParam(required = false) Integer declare_status,
            @RequestParam(required = false) String tx_date,
            @RequestParam(required = false) Long cid,
            @RequestParam(required = false) String bl_no,
            @RequestParam(required = false) String ib_date,
            @RequestParam(required = false) String ob_date,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("status", status);
            params.put("desAdd", des_add);
            params.put("declareType", declare_type);
            params.put("whs", whs);
            params.put("declareStatus", declare_status);
            params.put("txDate", tx_date);
            params.put("customerId", cid);
            params.put("blNo", bl_no);
            params.put("ibDate", ib_date);
            params.put("obDate", ob_date);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<Map<String, Object>> result = orderService.getAirfOrderList(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取沙特空运发货订单列表失败", e);
            return Result.error("获取订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取沙特空运到达订单列表（aire）
     * 对应PHP: orders.php case 'aire'
     */
    @GetMapping("/aire")
    public Result<PageResult<Map<String, Object>>> getAireOrderList(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer des_add,
            @RequestParam(required = false) Integer declare_type,
            @RequestParam(required = false) Integer declare_status,
            @RequestParam(required = false) Integer booking_no,
            @RequestParam(required = false) String tx_date,
            @RequestParam(required = false) String booking_date,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("status", status);
            params.put("desAdd", des_add);
            params.put("declareType", declare_type);
            params.put("declareStatus", declare_status);
            params.put("bookingNo", booking_no);
            params.put("txDate", tx_date);
            params.put("bookingDate", booking_date);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<Map<String, Object>> result = orderService.getAireOrderList(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取沙特空运到达订单列表失败", e);
            return Result.error("获取订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取沙特海运到达订单列表（seae）
     * 对应PHP: orders.php case 'seae_stop'
     */
    @GetMapping("/seae")
    public Result<PageResult<Map<String, Object>>> getSeaeOrderList(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer des_add,
            @RequestParam(required = false) Integer declare_type,
            @RequestParam(required = false) Integer declare_status,
            @RequestParam(required = false) String tx_date,
            @RequestParam(required = false) String loading_date,
            @RequestParam(required = false) Long cid,
            @RequestParam(required = false) String ib_date,
            @RequestParam(required = false) Integer booking_no,
            @RequestParam(required = false) String booking_date,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("status", status);
            params.put("desAdd", des_add);
            params.put("declareType", declare_type);
            params.put("declareStatus", declare_status);
            params.put("txDate", tx_date);
            params.put("loadingDate", loading_date);
            params.put("customerId", cid);
            params.put("ibDate", ib_date);
            params.put("bookingNo", booking_no);
            params.put("bookingDate", booking_date);
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<Map<String, Object>> result = orderService.getSeaeOrderList(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取沙特海运到达订单列表失败", e);
            return Result.error("获取订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 搜索订单（根据订单号和ASN号）
     */
    @GetMapping("/search")
    @RequiresPermission("search")
    public Result<List<Map<String, Object>>> searchOrderByOrderNoAndAsnNo(
            @RequestParam(required = false) String o,
            @RequestParam(required = false) String a,
            HttpServletRequest request) {
        try {
            Long customerId = (Long) request.getAttribute("customerId");
            List<Map<String, Object>> result = orderService.searchOrderByOrderNoAndAsnNo(o, a, customerId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("搜索订单失败", e);
            return Result.error("搜索订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取异常订单列表
     */
    @GetMapping("/unusual")
    @RequiresPermission("unusual")
    public Result<PageResult<Map<String, Object>>> getUnusualOrderList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            
            PageResult<Map<String, Object>> result = orderService.getUnusualOrderList(params);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取异常订单列表失败", e);
            return Result.error("获取异常订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 分页查询订单列表
     */
    @GetMapping("/list")
    public Result<PageResult<LxOrderList>> getOrderList(
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Integer shipType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer desAdd,
            @RequestParam(required = false) Integer declareType,
            @RequestParam(required = false) Integer declareStatus,
            @RequestParam(required = false) String txDate,
            @RequestParam(required = false) String blNo,
            @RequestParam(required = false) String obDate,
            @RequestParam(required = false) String ibDate,
            @RequestParam(required = false) String searchStartIbDate,
            @RequestParam(required = false) String searchEndIbDate,
            @RequestParam(required = false) Long yw,
            @RequestParam(required = false) Integer isPrice,
            @RequestParam(required = false) Integer isBill,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String flagAct,
            @RequestParam(required = false) Integer whId,
            @RequestParam(required = false) Integer isBrand,
            @RequestParam(required = false) Integer isRecv,
            @RequestParam(required = false) Integer isShipped,
            @RequestParam(required = false) Integer newStatus,
            @RequestParam(required = false) String sortProp,
            @RequestParam(required = false) String sortOrder,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", orderNo);
        params.put("customerId", customerId);
        params.put("shipType", shipType);
        params.put("status", status);
        params.put("desAdd", desAdd);
        params.put("declareType", declareType);
        params.put("declareStatus", declareStatus);
        params.put("txDate", txDate);
        params.put("blNo", blNo);
        params.put("obDate", obDate);
        params.put("ibDate", ibDate);
        params.put("searchStartIbDate", searchStartIbDate);
        params.put("searchEndIbDate", searchEndIbDate);
        params.put("yw", yw);
        params.put("isPrice", isPrice);
        params.put("isBill", isBill);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("flagAct", flagAct);
        params.put("whId", whId);
        params.put("isBrand", isBrand);
        params.put("isRecv", isRecv);
        params.put("isShipped", isShipped);
        params.put("newStatus", newStatus);
        params.put("sortProp", sortProp);
        params.put("sortOrder", sortOrder);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        
        // 根据用户组权限设置查询条件
        Integer userGroup = (Integer) request.getAttribute("userGroup");
        Long userId = (Long) request.getAttribute("userId");
        Long sessionCustomerId = (Long) request.getAttribute("customerId"); // 客户ID（如果是客户登录）
        
        // 判断是否为管理员组
        boolean isAdmin = isAdminGroup(userGroup);
        params.put("isAdmin", isAdmin);
        
        // 根据 flagAct 设置不同的查询条件
        String flagActStr = flagAct != null ? flagAct : "";
        
        if ("my".equals(flagActStr) || "mysea".equals(flagActStr) || "myuaeair".equals(flagActStr) || "myuaesea".equals(flagActStr)) {
            // 客户订单查询：根据客户ID查询
            if (sessionCustomerId != null && sessionCustomerId > 0) {
                params.put("customerId", sessionCustomerId);
                // 某些客户需要根据 add_uid 过滤（个人管个人订单）
                if (MGT_ORDER_BY_USER_CID.contains(sessionCustomerId)) {
                    // 特殊客户：需要同时满足customerId和addUid条件
                    Long sessionUserId = (Long) request.getAttribute("userId");
                    if (sessionUserId != null && sessionUserId > 0) {
                        params.put("addUid", sessionUserId);
                    }
                }
            } else {
                // 如果没有客户ID，返回空结果
                params.put("customerId", -1); // 设置为无效值，SQL 中会返回空结果
            }
        } else if (!isAdmin && userId != null) {
            // 非管理员组：根据 flagAct 使用不同的字段
            if ("ajax_get_list".equals(flagActStr)) {
                // ajax_get_list 使用 sales_uid
                params.put("salesUid", userId);
            } else {
                // list 和 list_test 使用 customer_list.user_id
                params.put("customerUserId", userId);
            }
        }
        
        PageResult<LxOrderList> result = orderService.getOrderList(params);
        return Result.success(result);
    }
    
    /**
     * 判断是否为管理员组
     */
    private boolean isAdminGroup(Integer userGroup) {
        // 管理员组：1, 3, 6, 11, 12, 14, 29, 35
        return userGroup != null && (userGroup == 1 || userGroup == 3 || userGroup == 6 || 
                userGroup == 11 || userGroup == 12 || userGroup == 14 || 
                userGroup == 29 || userGroup == 35);
    }
    
    /**
     * 根据订单号查询订单详情
     */
    @GetMapping("/detail")
    public Result<LxOrderList> getOrderDetail(@RequestParam(required = false) String orderNo, @RequestParam(required = false) Long id) {
        LxOrderList order = null;
        if (id != null && id > 0) {
            order = orderService.getById(id);
        } else if (orderNo != null && !orderNo.isEmpty()) {
            order = orderService.getOrderByNo(orderNo);
        }
        
        if (order != null) {
            return Result.success(order);
        }
        return Result.error("订单不存在");
    }
    
    /**
     * 创建订单
     */
    @PostMapping("/create")
    public Result<LxOrderList> createOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            Integer userGroup = (Integer) request.getAttribute("userGroup");
            Long sessionCustomerId = (Long) request.getAttribute("customerId");
            
            // 提取订单信息
            LxOrderList order = new LxOrderList();
            if (params.get("order") instanceof Map) {
                Map<String, Object> orderMap = (Map<String, Object>) params.get("order");
                // 将orderMap转换为LxOrderList对象
                // 这里可以使用BeanUtils或者手动映射
                order = convertMapToOrder(orderMap);
            } else if (params.get("order") instanceof LxOrderList) {
                order = (LxOrderList) params.get("order");
            } else {
                // 如果没有order字段，直接使用params作为订单信息
                order = convertMapToOrder(params);
            }
            
            // 提取仓库地址信息
            Map<String, Object> whAdd = null;
            if (params.get("whAdd") instanceof Map) {
                whAdd = (Map<String, Object>) params.get("whAdd");
            }
            
            LxOrderList result = orderService.createOrder(order, userId != null ? userId.intValue() : null, 
                    userGroup, sessionCustomerId, whAdd);
            
            return Result.success("Success.", result);
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return Result.error("Data Error: " + e.getMessage());
        }
    }
    
    /**
     * 将Map转换为LxOrderList对象（简化版，实际可以使用BeanUtils或MapStruct）
     */
    private LxOrderList convertMapToOrder(Map<String, Object> map) {
        LxOrderList order = new LxOrderList();
        // 这里可以使用反射或者手动映射字段
        // 为了简化，这里只映射常用字段
        if (map.get("orderNo") != null) {
            order.setOrderNo(map.get("orderNo").toString());
        }
        if (map.get("customerId") != null) {
            order.setCustomerId(Long.valueOf(map.get("customerId").toString()));
        }
        if (map.get("fbaNo") != null) {
            order.setFbaNo(map.get("fbaNo").toString());
        }
        if (map.get("shipType") != null) {
            order.setShipType(Integer.valueOf(map.get("shipType").toString()));
        }
        if (map.get("etaSz") != null) {
            order.setEtaSz(map.get("etaSz").toString());
        }
        if (map.get("isBrand") != null) {
            order.setIsBrand(Integer.valueOf(map.get("isBrand").toString()));
        }
        // 可以继续添加其他字段的映射
        return order;
    }
    
    /**
     * 更新订单
     */
    @PostMapping("/update")
    public Result<Boolean> updateOrder(@RequestBody LxOrderList order, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean result = orderService.updateOrder(order, userId != null ? userId.intValue() : null);
            if (result) {
                return Result.success("Success.", true);
            }
            return Result.error("Data Error");
        } catch (Exception e) {
            log.error("更新订单失败", e);
            return Result.error("Data Error");
        }
    }
    
    /**
     * 删除订单（逻辑删除）
     */
    @PostMapping("/delete")
    public Result<Boolean> deleteOrder(@RequestParam Long id, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean result = orderService.deleteOrder(id, userId != null ? userId.intValue() : null);
            if (result) {
                return Result.success("Success.", true);
            }
            return Result.error("Data Error");
        } catch (Exception e) {
            log.error("删除订单失败", e);
            if (e.getMessage() != null && e.getMessage().contains("已入仓")) {
                return Result.error("已入仓订单不能删除");
            }
            return Result.error("Data Error");
        }
    }
    
    /**
     * 获取所有订单状态列表
     */
    @GetMapping("/status/list")
    public Result<List<LxOrderStatus>> getOrderStatusList() {
        List<LxOrderStatus> statusList = orderStatusService.getAllStatusList();
        return Result.success(statusList);
    }
    
    /**
     * 批量删除订单
     */
    @PostMapping("/batch/delete")
    public Result<Boolean> batchDeleteOrders(@RequestBody List<Long> ids, HttpServletRequest request) {
        try {
            boolean result = orderService.batchDeleteOrders(ids);
            if (result) {
                // 记录操作日志（在Service层已记录，这里不需要再记录）
                return Result.success("Success.", true);
            }
            return Result.error("Data Error");
        } catch (Exception e) {
            log.error("批量删除订单失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量更新单价
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/price")
    public Result<Boolean> batchUpdatePrice(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            Object priceObj = params.get("price");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (priceObj == null) {
                return Result.error("请输入单价");
            }
            
            BigDecimal price;
            if (priceObj instanceof Number) {
                price = BigDecimal.valueOf(((Number) priceObj).doubleValue());
            } else {
                price = new BigDecimal(priceObj.toString());
            }
            
            boolean result = orderService.batchUpdatePrice(ids, price);
            if (result) {
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量更新单价", request);
                    }
                }
                return Result.success("批量更新单价成功", true);
            }
            return Result.error("批量更新单价失败");
        } catch (Exception e) {
            log.error("批量更新单价失败", e);
            return Result.error("批量更新单价失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单审核信息
     */
    @GetMapping("/check/info")
    @RequiresPermission("check")
    public Result<Map<String, Object>> getOrderCheckInfo(
            @RequestParam Long id,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getOrderCheckInfo(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取订单审核信息失败", e);
            return Result.error("获取订单审核信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 订单审核
     */
    @RequiresPermission("check")
    @PostMapping("/check")
    public Result<Boolean> checkOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long id = convertToLong(params.get("id"));
            if (id == null || id <= 0) {
                return Result.error("订单ID不能为空");
            }
            
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            boolean result = orderService.checkOrder(id, params, userId);
            if (result) {
                // 记录操作日志（在Service层已记录，这里不需要再记录）
                return Result.success("Success.", true);
            }
            return Result.error("Data Error");
        } catch (Exception e) {
            log.error("订单审核失败", e);
            if (e.getMessage() != null && e.getMessage().contains("已审核")) {
                return Result.error(e.getMessage());
            }
            return Result.error("Data Error");
        }
    }
    
    /**
     * 更新订单业务员
     */
    @PostMapping("/edit-staff")
    @RequiresPermission("edit_staff")
    public Result<String> updateOrderSalesUid(
            @RequestParam Long id,
            @RequestParam Long sales_uid,
            HttpServletRequest request) {
        try {
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.updateOrderSalesUid(id, sales_uid, userId);
            if (success) {
                return Result.success("Success.");
            } else {
                return Result.error("Data Error");
            }
        } catch (Exception e) {
            log.error("更新订单业务员失败", e);
            return Result.error("更新订单业务员失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取停止发货信息
     */
    @GetMapping("/stop-ship/info")
    @RequiresPermission("stopship")
    public Result<Map<String, Object>> getStopShipInfo(
            @RequestParam Long id,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = orderService.getStopShipInfo(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取停止发货信息失败", e);
            return Result.error("获取停止发货信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 停止发货
     */
    @PostMapping("/stop-ship")
    @RequiresPermission("stopship")
    public Result<String> stopShip(
            @RequestParam Long id,
            @RequestParam(required = false) String stop_ship_remarks,
            HttpServletRequest request) {
        try {
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.stopShip(id, stop_ship_remarks, userId);
            if (success) {
                return Result.success("Success");
            } else {
                return Result.error("Data Error");
            }
        } catch (Exception e) {
            log.error("停止发货失败", e);
            return Result.error("停止发货失败：" + e.getMessage());
        }
    }
    
    /**
     * 恢复发货
     */
    @PostMapping("/resume-ship")
    @RequiresPermission("re_stopship")
    public Result<String> resumeShip(
            @RequestParam Long id,
            HttpServletRequest request) {
        try {
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resumeShip(id, userId);
            if (success) {
                return Result.success("Success");
            } else {
                return Result.error("Data Error");
            }
        } catch (Exception e) {
            log.error("恢复发货失败", e);
            return Result.error("恢复发货失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单审核表单数据
     */
    @RequiresPermission("check")
    @GetMapping("/check/form")
    public Result<Map<String, Object>> getCheckForm(@RequestParam Long id) {
        try {
            LxOrderList order = orderService.getById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", order.getOrderNo());
            data.put("status", order.getStatus());
            data.put("remarks", order.getWmsRemarks());
            data.put("cusRemarks", order.getCusRemarks());
            data.put("isBrand", order.getIsBrand());
            data.put("shipType", order.getShipType());
            data.put("isSensitive", order.getIsSensitive());
            
            // 查询头程单号
            LxShipLog shipLog = shipLogMapper.selectFirstByOrderId(id);
            if (shipLog != null) {
                data.put("txNo", shipLog.getTxNo());
            }
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取订单审核表单数据失败", e);
            return Result.error("获取订单审核表单数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取待审核订单列表
     */
    @RequiresPermission("view")
    @GetMapping("/pending-check")
    public Result<List<LxOrderList>> getPendingCheckOrders(@RequestParam(required = false) Integer shipType,
                                                           @RequestParam(required = false) Integer desCountry) {
        try {
            Map<String, Object> params = new HashMap<>();
            if (shipType != null) {
                params.put("shipType", shipType);
            }
            if (desCountry != null) {
                params.put("desCountry", desCountry);
            }
            
            List<LxOrderList> orders = orderService.getPendingCheckOrders(params);
            return Result.success(orders);
        } catch (Exception e) {
            log.error("获取待审核订单列表失败", e);
            return Result.error("获取待审核订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 强制删除订单
     */
    @RequiresPermission("del")
    @PostMapping("/force-delete")
    public Result<Boolean> forceDeleteOrder(@RequestParam Long id, HttpServletRequest request) {
        try {
            boolean result = orderService.forceDeleteOrder(id);
            if (result) {
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    logUtil.logAction(userId, username, "order_list", id, "强制删除订单", request);
                }
                return Result.success("强制删除成功", true);
            }
            return Result.error("强制删除失败");
        } catch (Exception e) {
            log.error("强制删除订单失败", e);
            return Result.error("强制删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 打印入库标贴
     */
    @RequiresPermission("view")
    @GetMapping("/print-label")
    public Result<Map<String, Object>> printLabel(@RequestParam Long id) {
        try {
            LxOrderList order = orderService.getById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", order.getOrderNo());
            data.put("totalCtns", order.getTotalCtns());
            data.put("orderId", order.getId());
            
            // 生成条形码
            try {
                String barcodeContent = order.getOrderNo();
                if (barcodeContent != null && !barcodeContent.trim().isEmpty()) {
                    // 生成条形码文件（保存到uploads/barcode/目录）
                    // 注意：BarcodeUtil.createBarcodeWithText方法需要完整的目录路径
                    String projectRoot = System.getProperty("user.dir");
                    String uploadPath = projectRoot + "/uploads/barcode/";
                    
                    // 确保目录存在
                    java.io.File uploadDir = new java.io.File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }
                    
                    String barcodePath = barcodeUtil.createBarcodeWithText(barcodeContent, uploadPath);
                    
                    // 返回条形码文件路径（相对路径，用于前端访问）
                    if (barcodePath != null && barcodePath.startsWith(projectRoot)) {
                        String relativePath = barcodePath.substring(projectRoot.length());
                        if (relativePath.startsWith("/")) {
                            relativePath = relativePath.substring(1);
                        }
                        // 返回相对路径，前端可以通过 /uploads/barcode/xxx.png 访问
                        data.put("barcodeUrl", "/" + relativePath.replace("\\", "/"));
                        data.put("barcodePath", relativePath.replace("\\", "/"));
                    } else {
                        // 如果路径处理失败，直接返回文件名
                        String fileName = barcodeContent + ".png";
                        data.put("barcodeUrl", "/uploads/barcode/" + fileName);
                        data.put("barcodePath", "uploads/barcode/" + fileName);
                    }
                }
            } catch (Exception e) {
                log.warn("生成条形码失败: orderNo={}", order.getOrderNo(), e);
                // 条形码生成失败不影响主要功能，继续返回订单信息
            }
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取打印入库标贴数据失败", e);
            return Result.error("获取打印入库标贴数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量下载装箱单
     */
    @RequiresPermission("view")
    @PostMapping("/batch/download-pl")
    public org.springframework.http.ResponseEntity<org.springframework.core.io.Resource> batchDownloadPackingList(
            @RequestBody java.util.List<Long> ids,
            HttpServletRequest request) {
        try {
            if (ids == null || ids.isEmpty()) {
                return org.springframework.http.ResponseEntity.badRequest().build();
            }
            
            // 查询订单的装箱单文件（type=7, tb_name='order_list'）
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxAttr> wrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            wrapper.eq("type", 7)
                   .eq("tb_name", "order_list")
                   .in("tb_id", ids);
            
            java.util.List<com.adk.backend.entity.LxAttr> attrList = attrMapper.selectList(wrapper);
            if (attrList == null || attrList.isEmpty()) {
                return org.springframework.http.ResponseEntity.notFound().build();
            }
            
            // 获取订单号映射（用于文件命名）
            java.util.Map<Long, String> orderNoMap = new java.util.HashMap<>();
            java.util.List<com.adk.backend.entity.LxOrderList> orders = orderService.listByIds(ids);
            for (com.adk.backend.entity.LxOrderList order : orders) {
                if (order.getOrderNo() != null) {
                    orderNoMap.put(order.getId(), order.getOrderNo());
                }
            }
            
            // 收集文件路径
            java.util.List<String> filePaths = new java.util.ArrayList<>();
            for (com.adk.backend.entity.LxAttr attr : attrList) {
                if (attr.getAttr() != null && !attr.getAttr().trim().isEmpty()) {
                    String filePath = attr.getAttr().trim();
                    // 处理路径（移除开头的./或/）
                    if (filePath.startsWith("./")) {
                        filePath = filePath.substring(2);
                    } else if (filePath.startsWith("/")) {
                        filePath = filePath.substring(1);
                    }
                    
                    // 检查文件是否存在，如果不存在尝试从备份目录查找
                    java.io.File file = new java.io.File(filePath);
                    if (!file.exists()) {
                        // 尝试从orders_backup目录查找
                        String backupPath = filePath.replace("/orders/", "/orders_backup/");
                        java.io.File backupFile = new java.io.File(backupPath);
                        if (backupFile.exists()) {
                            filePath = backupPath;
                        } else {
                            // 文件不存在，跳过
                            continue;
                        }
                    }
                    
                    filePaths.add(filePath);
                }
            }
            
            if (filePaths.isEmpty()) {
                return org.springframework.http.ResponseEntity.notFound().build();
            }
            
            // 创建临时ZIP文件
            Long userId = (Long) request.getAttribute("userId");
            String zipFileName = "uploads/tmp/" + System.currentTimeMillis() + "_" + (userId != null ? userId : 0) + ".zip";
            java.io.File zipFile = fileUploadUtil.createZipFile(filePaths, zipFileName);
            
            org.springframework.core.io.Resource resource = new org.springframework.core.io.FileSystemResource(zipFile);
            String downloadFileName = "batch_download_pl_" + System.currentTimeMillis() + ".zip";
            
            return org.springframework.http.ResponseEntity.ok()
                    .header(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION, 
                            "attachment; filename=\"" + downloadFileName + "\"")
                    .contentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            log.error("批量下载装箱单失败", e);
            return org.springframework.http.ResponseEntity.status(
                    org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 批量导出货物明细
     */
    @RequiresPermission("view")
    @PostMapping("/batch/export-details")
    public void batchExportDetails(
            @RequestBody java.util.List<Long> ids,
            HttpServletResponse response) {
        try {
            if (ids == null || ids.isEmpty()) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "请选择要导出的订单");
                return;
            }
            
            // 查询订单详情
            java.util.List<com.adk.backend.entity.LxOrderList> orders = orderService.listByIds(ids);
            if (orders == null || orders.isEmpty()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到订单数据");
                return;
            }
            
            // 准备表头（根据PHP代码的batch_download，空运和海运的表头不同）
            // 这里使用空运的表头
            String[] headers = {
                "客户名称", "入仓号", "箱数", "计费重", "入库日期", "出库日期", "头程单号", 
                "业务员", "派送地址", "派送地址备注", "派送城市", "订单状态", "预约日期", 
                "状态名称", "状态时间", "派送方式", "FBA单号", "备注"
            };
            
            // 转换数据格式
            java.util.List<java.util.Map<String, Object>> exportData = new java.util.ArrayList<>();
            for (com.adk.backend.entity.LxOrderList order : orders) {
                java.util.Map<String, Object> row = new java.util.HashMap<>();
                
                // 查询客户信息
                com.adk.backend.entity.LxCustomerList customer = null;
                if (order.getCustomerId() != null) {
                    customer = customerListMapper.selectById(order.getCustomerId());
                }
                
                // 查询业务员信息
                String salesUsername = "";
                if (order.getSalesUid() != null) {
                    com.adk.backend.entity.LxAdmin admin = adminMapper.selectById(order.getSalesUid());
                    if (admin != null) {
                        salesUsername = admin.getUsername() != null ? admin.getUsername() : "";
                    }
                }
                
                // 查询订单状态信息
                String statusName = "";
                if (order.getStatus() != null) {
                    com.adk.backend.entity.LxOrderStatus status = orderStatusService.getById(order.getStatus());
                    if (status != null) {
                        statusName = status.getStatusName() != null ? status.getStatusName() : "";
                    }
                }
                
                // 查询预约信息
                String bookingDate = "";
                com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxBookingList> bookingWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
                bookingWrapper.eq("order_id", order.getId()).last("LIMIT 1");
                com.adk.backend.entity.LxBookingList booking = bookingListMapper.selectOne(bookingWrapper);
                if (booking != null && booking.getBookingDate() != null) {
                    bookingDate = booking.getBookingDate();
                }
                
                // 查询订单轨迹（最新状态时间）
                String statusTime = "";
                com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxOrderTracking> trackingWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
                trackingWrapper.eq("order_id", order.getId())
                               .eq("status_code", order.getStatus())
                               .eq("is_show", 1)
                               .orderByDesc("id")
                               .last("LIMIT 1");
                com.adk.backend.entity.LxOrderTracking tracking = orderTrackingMapper.selectOne(trackingWrapper);
                if (tracking != null && tracking.getStatusTime() != null) {
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
                    statusTime = sdf.format(new java.util.Date(tracking.getStatusTime() * 1000L));
                }
                
                // 查询发货日志（头程单号、出库日期）
                String txNo = "";
                String txDate = "";
                com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxShipLog> shipLogWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
                shipLogWrapper.eq("ol_id", order.getId()).last("LIMIT 1");
                com.adk.backend.entity.LxShipLog shipLog = shipLogMapper.selectOne(shipLogWrapper);
                if (shipLog != null) {
                    txNo = shipLog.getTxNo() != null ? shipLog.getTxNo() : "";
                    if (shipLog.getTxDate() != null && shipLog.getTxDate() > 0) {
                        txDate = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(shipLog.getTxDate() * 1000L));
                    }
                }
                
                // 填充数据
                row.put("客户名称", customer != null && customer.getCusCode() != null ? customer.getCusCode() : "");
                row.put("入仓号", order.getOrderNo() != null ? order.getOrderNo() : "");
                row.put("箱数", order.getTotalCtns() != null ? order.getTotalCtns() : 0);
                row.put("计费重", order.getShipWeigth() != null ? order.getShipWeigth() : BigDecimal.ZERO);
                row.put("入库日期", order.getRecvTime() != null ? 
                    new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(order.getRecvTime() * 1000L)) : "");
                row.put("出库日期", txDate);
                row.put("头程单号", txNo);
                row.put("业务员", salesUsername);
                row.put("派送地址", order.getDesAddress() != null ? order.getDesAddress() : "");
                row.put("派送地址备注", ""); // LxOrderList实体中没有此字段
                row.put("派送城市", getDesCityName(order.getDesCity()));
                row.put("订单状态", order.getStatus() != null ? order.getStatus().toString() : "");
                row.put("预约日期", bookingDate);
                row.put("状态名称", statusName);
                row.put("状态时间", statusTime);
                row.put("派送方式", getDesAddName(order.getDesAdd()));
                row.put("FBA单号", order.getFbaNo() != null ? order.getFbaNo() : "");
                row.put("备注", ""); // LxOrderList实体中没有此字段
                
                exportData.add(row);
            }
            
            // 生成文件名
            String fileName = "Order_Details_" + new java.text.SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
            
            // 导出Excel
            excelUtil.exportExcel(response, fileName, headers, exportData);
        } catch (Exception e) {
            log.error("批量导出货物明细失败", e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败：" + e.getMessage());
            } catch (java.io.IOException ioException) {
                log.error("发送错误响应失败", ioException);
            }
        }
    }
    
    /**
     * 获取派送城市名称
     */
    private String getDesCityName(Integer desCity) {
        if (desCity == null) return "";
        switch (desCity) {
            case 1: return "利雅得及周边";
            case 2: return "达曼及周边";
            case 3: return "吉达及周边";
            case 4: return "新城市及周边";
            case 5: return "其他";
            default: return "";
        }
    }
    
    /**
     * 获取派送方式名称
     */
    private String getDesAddName(Integer desAdd) {
        if (desAdd == null) return "";
        switch (desAdd) {
            case 1: return "Aiduk-Shelf";
            case 2: return "Aiduk-DS";
            case 3: return "Amazon";
            case 4: return "Noon Appointment";
            case 5: return "Private Address";
            case 6: return "Self-pickup";
            case 7: return "B2C";
            default: return "";
        }
    }
    
    @Autowired
    private com.adk.backend.mapper.CustomerListMapper customerListMapper;
    
    @Autowired
    private com.adk.backend.mapper.AdminMapper adminMapper;
    
    @Autowired
    private com.adk.backend.mapper.BookingListMapper bookingListMapper;
    
    @Autowired
    private com.adk.backend.mapper.OrderTrackingMapper orderTrackingMapper;
    
    /**
     * 批量导出货物轨迹
     */
    @RequiresPermission("view")
    @PostMapping("/batch/export-tracking")
    public void batchExportTracking(
            @RequestBody java.util.List<Long> ids,
            HttpServletResponse response) {
        try {
            if (ids == null || ids.isEmpty()) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "请选择要导出的订单");
                return;
            }
            
            // 准备表头
            String[] headers = {"Order_NO", "Status", "Time"};
            
            // 转换数据格式
            java.util.List<java.util.Map<String, Object>> exportData = new java.util.ArrayList<>();
            
            // 查询所有订单的轨迹记录
            for (Long orderId : ids) {
                // 查询订单信息
                com.adk.backend.entity.LxOrderList order = orderService.getById(orderId);
                if (order == null || order.getOrderNo() == null) {
                    continue;
                }
                
                // 查询该订单的所有轨迹记录
                com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.adk.backend.entity.LxOrderTracking> trackingWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
                trackingWrapper.eq("order_id", orderId)
                               .orderByAsc("order_id", "status_code", "id");
                
                java.util.List<com.adk.backend.entity.LxOrderTracking> trackingList = orderTrackingMapper.selectList(trackingWrapper);
                
                if (trackingList == null || trackingList.isEmpty()) {
                    // 如果没有轨迹记录，至少添加一条订单号记录
                    java.util.Map<String, Object> row = new java.util.HashMap<>();
                    row.put("Order_NO", order.getOrderNo());
                    row.put("Status", "");
                    row.put("Time", "");
                    exportData.add(row);
                } else {
                    // 为每条轨迹记录创建一行
                    for (com.adk.backend.entity.LxOrderTracking tracking : trackingList) {
                        java.util.Map<String, Object> row = new java.util.HashMap<>();
                        row.put("Order_NO", order.getOrderNo());
                        
                        // 状态：优先使用remarks，否则使用status_name
                        String status = "";
                        if (tracking.getRemarks() != null && !tracking.getRemarks().trim().isEmpty()) {
                            status = tracking.getRemarks().trim();
                        } else {
                            // 查询状态名称
                            if (tracking.getStatusCode() != null) {
                                com.adk.backend.entity.LxOrderStatus orderStatus = orderStatusService.getById(tracking.getStatusCode());
                                if (orderStatus != null && orderStatus.getStatusName() != null) {
                                    status = orderStatus.getStatusName();
                                }
                            }
                        }
                        row.put("Status", status);
                        
                        // 时间：格式为 MM-dd HH:mm
                        String timeStr = "";
                        if (tracking.getStatusTime() != null && tracking.getStatusTime() > 0) {
                            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM-dd HH:mm");
                            timeStr = sdf.format(new java.util.Date(tracking.getStatusTime() * 1000L));
                        }
                        row.put("Time", timeStr);
                        
                        exportData.add(row);
                    }
                }
            }
            
            if (exportData.isEmpty()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到轨迹数据");
                return;
            }
            
            // 生成文件名
            String fileName = "Order_Tracking_" + new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
            
            // 导出Excel
            excelUtil.exportExcel(response, fileName, headers, exportData);
        } catch (Exception e) {
            log.error("批量导出货物轨迹失败", e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败：" + e.getMessage());
            } catch (java.io.IOException ioException) {
                log.error("发送错误响应失败", ioException);
            }
        }
    }
    
    /**
     * 批量更新订单状态
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-status")
    public Result<Boolean> batchUpdateStatus(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            Integer status = (Integer) params.get("status");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (status == null) {
                return Result.error("请选择要更新的状态");
            }
            
            boolean result = orderService.batchUpdateStatus(ids, status);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量更新订单状态", request);
                    }
                }
                return Result.success("批量更新状态成功", true);
            }
            return Result.error("批量更新状态失败");
        } catch (Exception e) {
            log.error("批量更新订单状态失败", e);
            return Result.error("批量更新状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量更新预约状态
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-booking")
    public Result<Boolean> batchUpdateBooking(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String bookingNo = (String) params.get("bookingNo");
            Integer bookingType = (Integer) params.get("bookingType");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (bookingNo == null || bookingNo.trim().isEmpty()) {
                return Result.error("请输入预约码");
            }
            
            boolean result = orderService.batchUpdateBooking(ids, bookingNo, bookingType);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量更新预约状态", request);
                    }
                }
                return Result.success("批量更新预约状态成功", true);
            }
            return Result.error("批量更新预约状态失败");
        } catch (Exception e) {
            log.error("批量更新预约状态失败", e);
            return Result.error("批量更新预约状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量装柜
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-loading")
    public Result<Boolean> batchUpdateLoading(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            
            boolean result = orderService.batchUpdateLoading(ids, params);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量装柜", request);
                    }
                }
                return Result.success("批量装柜成功", true);
            }
            return Result.error("批量装柜失败");
        } catch (Exception e) {
            log.error("批量装柜失败", e);
            return Result.error("批量装柜失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量更新头程单号
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-tx-no")
    public Result<Boolean> batchUpdateTxNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String txNo = (String) params.get("txNo");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (txNo == null || txNo.trim().isEmpty()) {
                return Result.error("请输入头程单号");
            }
            
            boolean result = orderService.batchUpdateTxNo(ids, txNo);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量更新头程单号", request);
                    }
                }
                return Result.success("批量更新头程单号成功", true);
            }
            return Result.error("批量更新头程单号失败");
        } catch (Exception e) {
            log.error("批量更新头程单号失败", e);
            return Result.error("批量更新头程单号失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量更新航班信息
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-flight")
    public Result<Boolean> batchUpdateFlight(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String flightNo = (String) params.get("flightNo");
            String flightDate = (String) params.get("flightDate");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (flightNo == null || flightNo.trim().isEmpty()) {
                return Result.error("请输入航班号");
            }
            if (flightDate == null || flightDate.trim().isEmpty()) {
                return Result.error("请选择航班日期");
            }
            
            boolean result = orderService.batchUpdateFlight(ids, flightNo, flightDate);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量更新航班信息", request);
                    }
                }
                return Result.success("批量更新航班信息成功", true);
            }
            return Result.error("批量更新航班信息失败");
        } catch (Exception e) {
            log.error("批量更新航班信息失败", e);
            return Result.error("批量更新航班信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量到达
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-arrival")
    public Result<Boolean> batchUpdateArrival(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String arrivalDate = (String) params.get("arrivalDate");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (arrivalDate == null || arrivalDate.trim().isEmpty()) {
                return Result.error("请选择到达日期");
            }
            
            boolean result = orderService.batchUpdateArrival(ids, arrivalDate);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量到达", request);
                    }
                }
                return Result.success("批量到达成功", true);
            }
            return Result.error("批量到达失败");
        } catch (Exception e) {
            log.error("批量到达失败", e);
            return Result.error("批量到达失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量清关
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-clearance")
    public Result<Boolean> batchUpdateClearance(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String clearanceDate = (String) params.get("clearanceDate");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (clearanceDate == null || clearanceDate.trim().isEmpty()) {
                return Result.error("请选择清关日期");
            }
            
            boolean result = orderService.batchUpdateClearance(ids, clearanceDate);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量清关", request);
                    }
                }
                return Result.success("批量清关成功", true);
            }
            return Result.error("批量清关失败");
        } catch (Exception e) {
            log.error("批量清关失败", e);
            return Result.error("批量清关失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量设置品牌备注
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-brand-remarks")
    public Result<Boolean> batchUpdateBrandRemarks(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String isBrandRemarks = (String) params.get("isBrandRemarks");
            Integer isSensitive = (Integer) params.get("isSensitive");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (isBrandRemarks == null || isBrandRemarks.trim().isEmpty()) {
                return Result.error("请输入品牌备注");
            }
            
            boolean result = orderService.batchUpdateBrandRemarks(ids, isBrandRemarks, isSensitive);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量设置品牌备注", request);
                    }
                }
                return Result.success("批量设置品牌备注成功", true);
            }
            return Result.error("批量设置品牌备注失败");
        } catch (Exception e) {
            log.error("批量设置品牌备注失败", e);
            return Result.error("批量设置品牌备注失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量修改交货方式
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-order-type")
    public Result<Boolean> batchUpdateOrderType(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            Integer orderType = (Integer) params.get("orderType");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (orderType == null) {
                return Result.error("请选择交货方式");
            }
            
            boolean result = orderService.batchUpdateOrderType(ids, orderType);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量修改交货方式", request);
                    }
                }
                return Result.success("批量修改交货方式成功", true);
            }
            return Result.error("批量修改交货方式失败");
        } catch (Exception e) {
            log.error("批量修改交货方式失败", e);
            return Result.error("批量修改交货方式失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量签收
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-recvd")
    public Result<Boolean> batchUpdateRecvd(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String recvdDate = (String) params.get("recvdDate");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (recvdDate == null || recvdDate.trim().isEmpty()) {
                return Result.error("请选择签收日期");
            }
            
            boolean result = orderService.batchUpdateRecvd(ids, recvdDate);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量签收", request);
                    }
                }
                return Result.success("批量签收成功", true);
            }
            return Result.error("批量签收失败");
        } catch (Exception e) {
            log.error("批量签收失败", e);
            return Result.error("批量签收失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量盘点完成
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-pd")
    public Result<Boolean> batchUpdatePd(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String pdDate = (String) params.get("pdDate");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (pdDate == null || pdDate.trim().isEmpty()) {
                return Result.error("请选择盘点日期");
            }
            
            boolean result = orderService.batchUpdatePd(ids, pdDate);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量盘点完成", request);
                    }
                }
                return Result.success("批量盘点完成成功", true);
            }
            return Result.error("批量盘点完成失败");
        } catch (Exception e) {
            log.error("批量盘点完成失败", e);
            return Result.error("批量盘点完成失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量到达海外仓
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-arrival-overseas")
    public Result<Boolean> batchUpdateArrivalOverseas(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String arrivalDate = (String) params.get("arrivalDate");
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要更新的订单");
            }
            if (arrivalDate == null || arrivalDate.trim().isEmpty()) {
                return Result.error("请选择到达日期");
            }
            
            boolean result = orderService.batchUpdateArrivalOverseas(ids, arrivalDate);
            if (result) {
                // 记录操作日志
                Long userId = (Long) request.getAttribute("userId");
                String username = (String) request.getAttribute("username");
                if (userId != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userId, username, "order_list", id, "批量到达海外仓", request);
                    }
                }
                return Result.success("批量到达海外仓成功", true);
            }
            return Result.error("批量到达海外仓失败");
        } catch (Exception e) {
            log.error("批量到达海外仓失败", e);
            return Result.error("批量到达海外仓失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出订单列表
     */
    @GetMapping("/export")
    public void exportOrders(
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Integer shipType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String flagAct,
            HttpServletResponse response) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("orderNo", orderNo);
            params.put("customerId", customerId);
            params.put("shipType", shipType);
            params.put("status", status);
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("flagAct", flagAct);
            params.put("pageNum", 1);
            params.put("pageSize", 10000); // 导出所有数据
            
            PageResult<LxOrderList> pageResult = orderService.getOrderList(params);
            List<Map<String, Object>> data = new ArrayList<>();
            
            // 转换数据格式
            for (LxOrderList order : pageResult.getList()) {
                Map<String, Object> row = new HashMap<>();
                row.put("订单号", order.getOrderNo());
                row.put("客户简称", order.getCusShort());
                row.put("FBA单号", order.getFbaNo());
                row.put("运输方式", getShipTypeName(order.getShipType()));
                row.put("总箱数", order.getTotalCtns());
                row.put("计费重量", order.getShipWeigth());
                row.put("状态", getStatusName(order.getStatus()));
                row.put("创建时间", order.getAddTime());
                data.add(row);
            }
            
            String[] headers = {"订单号", "客户简称", "FBA单号", "运输方式", "总箱数", "计费重量", "状态", "创建时间"};
            excelUtil.exportExcel(response, "订单列表", headers, data);
        } catch (Exception e) {
            log.error("导出订单失败", e);
            try {
                response.getWriter().write("导出失败：" + e.getMessage());
            } catch (IOException ioException) {
                log.error("写入错误信息失败", ioException);
            }
        }
    }
    
    private String getShipTypeName(Integer type) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "沙特空运");
        map.put(2, "沙特海运拼柜");
        map.put(3, "阿联酋空运");
        map.put(4, "阿联酋海运");
        map.put(7, "沙特海运整柜");
        return map.getOrDefault(type, "未知");
    }
    
    private String getStatusName(Integer status) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "待处理");
        map.put(2, "处理中");
        map.put(3, "待收货");
        map.put(4, "已收货");
        return map.getOrDefault(status, "未知");
    }
    
    /**
     * 辅助方法：将对象安全地转换为 Long 类型
     */
    private Long convertToLong(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof Long) {
            return (Long) obj;
        }
        if (obj instanceof Integer) {
            return ((Integer) obj).longValue();
        }
        if (obj instanceof Number) {
            return ((Number) obj).longValue();
        }
        try {
            return Long.parseLong(obj.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }
    
    /**
     * 辅助方法：将列表中的元素安全地转换为 Long 类型
     * 处理 JSON 反序列化时可能出现的 Integer 类型
     */
    private List<Long> convertToLongList(Object idsObj) {
        if (idsObj == null) {
            return new ArrayList<>();
        }
        
        List<Long> result = new ArrayList<>();
        if (idsObj instanceof List) {
            List<?> list = (List<?>) idsObj;
            for (Object item : list) {
                if (item instanceof Long) {
                    result.add((Long) item);
                } else if (item instanceof Integer) {
                    result.add(((Integer) item).longValue());
                } else if (item instanceof Number) {
                    result.add(((Number) item).longValue());
                }
            }
        }
        return result;
    }
    
    /**
     * 0.5进位方法（向上取整到0.5的倍数）
     */
    private BigDecimal upto(BigDecimal value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        // 乘以2，向上取整，再除以2
        return value.multiply(new BigDecimal("2"))
            .setScale(0, BigDecimal.ROUND_UP)
            .divide(new BigDecimal("2"), 1, BigDecimal.ROUND_HALF_UP);
    }
    
    /**
     * 海运计费重进位方法（向上取整到0.1的倍数）
     */
    private BigDecimal uptoSeaGw(BigDecimal value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        return value.setScale(1, BigDecimal.ROUND_UP);
    }
    
    /**
     * 批量导出计费重明细
     */
    @RequiresPermission("view")
    @PostMapping("/batch/export-weight")
    public void batchExportWeight(@RequestBody Map<String, Object> params, HttpServletResponse response) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            
            if (ids == null || ids.isEmpty()) {
                response.getWriter().write("请选择要导出的订单");
                return;
            }
            
            // 查询接收日志（关联订单信息）
            List<Map<String, Object>> recvLogs = recvLogsMapper.selectByOrderIdsWithOrderInfo(ids);
            
            if (recvLogs == null || recvLogs.isEmpty()) {
                response.getWriter().write("所选订单没有接收日志数据");
                return;
            }
            
            // 准备表头
            String[] headers = {"入仓号", "箱号", "长(CM)", "宽(CM)", "高(CM)", "毛重(Kg)", "箱数", 
                "毛重(0.5进位)", "体积重", "计费重", "订单计费重"};
            
            // 转换数据格式
            List<Map<String, Object>> exportData = new ArrayList<>();
            String lastOrderNo = "";
            
            for (Map<String, Object> log : recvLogs) {
                Map<String, Object> row = new HashMap<>();
                
                String orderNo = (String) log.get("order_no");
                Integer ctnNo = (Integer) log.get("ctn_no");
                BigDecimal ctnL = (BigDecimal) log.get("ctn_l");
                BigDecimal ctnW = (BigDecimal) log.get("ctn_w");
                BigDecimal ctnH = (BigDecimal) log.get("ctn_h");
                BigDecimal ctnWeight = (BigDecimal) log.get("ctn_weight");
                Integer totalCtns = (Integer) log.get("total_ctns");
                Integer shipWeightType = (Integer) log.get("ship_weight_type");
                BigDecimal shipWeigth = (BigDecimal) log.get("ship_weigth");
                Integer shipType = (Integer) log.get("ship_type");
                
                // 基本数据
                row.put("入仓号", orderNo != null ? orderNo : "");
                row.put("箱号", ctnNo != null ? ctnNo : 0);
                row.put("长(CM)", ctnL != null ? ctnL : BigDecimal.ZERO);
                row.put("宽(CM)", ctnW != null ? ctnW : BigDecimal.ZERO);
                row.put("高(CM)", ctnH != null ? ctnH : BigDecimal.ZERO);
                row.put("毛重(Kg)", ctnWeight != null ? ctnWeight : BigDecimal.ZERO);
                row.put("箱数", totalCtns != null ? totalCtns : 0);
                
                // 计算毛重(0.5进位)
                BigDecimal gw = upto(ctnWeight != null ? ctnWeight : BigDecimal.ZERO);
                row.put("毛重(0.5进位)", gw);
                
                // 计算体积重
                BigDecimal vw = BigDecimal.ZERO;
                if (ctnL != null && ctnW != null && ctnH != null) {
                    BigDecimal volume = ctnL.multiply(ctnW).multiply(ctnH);
                    
                    // 根据ship_weight_type决定除数
                    if (shipWeightType != null && (shipWeightType == 1 || shipWeightType == 3)) {
                        // 除5000
                        vw = upto(volume.divide(new BigDecimal("5000"), 2, BigDecimal.ROUND_HALF_UP));
                    } else {
                        // 除6000
                        vw = upto(volume.divide(new BigDecimal("6000"), 2, BigDecimal.ROUND_HALF_UP));
                    }
                }
                row.put("体积重", vw);
                
                // 计算计费重
                BigDecimal shipWeight = BigDecimal.ZERO;
                if (shipType != null && (shipType == 2 || shipType == 7)) {
                    // 海运：重新计算体积重（m³）和毛重
                    if (ctnL != null && ctnW != null && ctnH != null) {
                        BigDecimal volumeM3 = ctnL.multiply(ctnW).multiply(ctnH)
                            .divide(new BigDecimal("1000000"), 3, BigDecimal.ROUND_HALF_UP);
                        vw = uptoSeaGw(volumeM3);
                        row.put("体积重", vw);
                    }
                    if (ctnWeight != null) {
                        gw = uptoSeaGw(ctnWeight.divide(new BigDecimal("400"), 3, BigDecimal.ROUND_HALF_UP));
                        row.put("毛重(0.5进位)", gw);
                    }
                    // 海运不计费重
                    row.put("计费重", "");
                } else {
                    // 空运：取毛重和体积重的较大值
                    shipWeight = gw.compareTo(vw) > 0 ? gw : vw;
                    row.put("计费重", shipWeight);
                }
                
                // 订单计费重（只在订单变更时显示）
                String currentOrderNo = orderNo != null ? orderNo : "";
                if (!currentOrderNo.equals(lastOrderNo)) {
                    lastOrderNo = currentOrderNo;
                    row.put("订单计费重", shipWeigth != null ? shipWeigth : BigDecimal.ZERO);
                } else {
                    row.put("订单计费重", "");
                }
                
                exportData.add(row);
            }
            
            // 生成文件名
            String fileName = "计费重明细_" + new java.text.SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
            
            // 导出Excel
            excelUtil.exportExcel(response, fileName, headers, exportData);
        } catch (Exception e) {
            log.error("导出计费重明细失败", e);
            try {
                response.getWriter().write("导出失败：" + e.getMessage());
            } catch (IOException ioException) {
                log.error("写入错误信息失败", ioException);
            }
        }
    }
    
    /**
     * 批量国内查验
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/cn-check")
    public Result<Boolean> batchCnCheck(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> ids = convertToLongList(params.get("ids"));
            String checkDate = (String) params.get("checkDate");
            String remarks = (String) params.get("remarks");
            Integer shipType = params.get("shipType") != null ? ((Number) params.get("shipType")).intValue() : null;
            
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要操作的订单");
            }
            if (checkDate == null || checkDate.trim().isEmpty()) {
                return Result.error("请输入查验日期");
            }
            
            // 获取用户ID
            Long userIdLong = (Long) request.getAttribute("userId");
            Integer userId = userIdLong != null ? userIdLong.intValue() : null;
            String username = (String) request.getAttribute("username");
            
            boolean result = orderService.batchCnCheck(ids, checkDate, remarks, shipType, userId);
            if (result) {
                // 记录操作日志
                if (userIdLong != null && username != null) {
                    for (Long id : ids) {
                        logUtil.logAction(userIdLong, username, "order_list", id, "批量国内查验:" + checkDate + (remarks != null && !remarks.trim().isEmpty() ? ", " + remarks : ""), request);
                    }
                }
                return Result.success("批量国内查验成功", true);
            }
            return Result.error("批量国内查验失败");
        } catch (Exception e) {
            log.error("批量国内查验失败", e);
            return Result.error("批量国内查验失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量更新航班信息（完整版 - 包含提单号、件数、重量等）
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-flight-info")
    public Result<Boolean> batchUpdateFlightInfo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> orderIds = convertToLongList(params.get("orderIds"));
            
            if (orderIds == null || orderIds.isEmpty()) {
                return Result.error("请选择要操作的订单");
            }
            
            // 获取用户ID
            Long userIdLong = (Long) request.getAttribute("userId");
            Integer userId = userIdLong != null ? userIdLong.intValue() : null;
            String username = (String) request.getAttribute("username");
            
            boolean result = orderService.batchUpdateFlightInfo(orderIds, params, userId);
            if (result) {
                // 记录操作日志
                if (userIdLong != null && username != null) {
                    for (Long id : orderIds) {
                        String blNo = params.get("blNo") != null ? params.get("blNo").toString() : "";
                        logUtil.logAction(userIdLong, username, "order_list", id, "批量更新航班信息:" + blNo, request);
                    }
                }
                return Result.success("批量更新航班信息成功", true);
            }
            return Result.error("批量更新航班信息失败");
        } catch (Exception e) {
            log.error("批量更新航班信息失败", e);
            return Result.error("批量更新航班信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量修改二程预配
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/update-second-flight")
    public Result<Boolean> batchUpdateSecondFlight(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> orderIds = convertToLongList(params.get("orderIds"));
            String flightDate2 = (String) params.get("flightDate2");
            String flightDateTime2 = (String) params.get("flightDateTime2");
            String remarks = (String) params.get("remarks");
            
            if (orderIds == null || orderIds.isEmpty()) {
                return Result.error("请选择要操作的订单");
            }
            if (flightDate2 == null || flightDate2.trim().isEmpty()) {
                return Result.error("请输入二程预配日期");
            }
            if (flightDateTime2 == null || flightDateTime2.trim().isEmpty()) {
                return Result.error("请输入二程预配时间");
            }
            
            // 获取用户ID
            Long userIdLong = (Long) request.getAttribute("userId");
            Integer userId = userIdLong != null ? userIdLong.intValue() : null;
            String username = (String) request.getAttribute("username");
            
            boolean result = orderService.batchUpdateSecondFlight(orderIds, flightDate2, flightDateTime2, remarks, userId);
            if (result) {
                // 记录操作日志
                if (userIdLong != null && username != null) {
                    for (Long id : orderIds) {
                        logUtil.logAction(userIdLong, username, "order_list", id, "批量修改二程预配:" + flightDate2 + " " + flightDateTime2, request);
                    }
                }
                return Result.success("批量修改二程预配成功", true);
            }
            return Result.error("批量修改二程预配失败");
        } catch (Exception e) {
            log.error("批量修改二程预配失败", e);
            return Result.error("批量修改二程预配失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量联程头程起飞
     */
    @RequiresPermission("edit")
    @PostMapping("/batch/first-flight-takeoff")
    public Result<Boolean> batchFirstFlightTakeoff(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            List<Long> orderIds = convertToLongList(params.get("orderIds"));
            String flightDate = (String) params.get("flightDate");
            String flightDateTime = (String) params.get("flightDateTime");
            String remarks = (String) params.get("remarks");
            
            if (orderIds == null || orderIds.isEmpty()) {
                return Result.error("请选择要操作的订单");
            }
            if (flightDate == null || flightDate.trim().isEmpty()) {
                return Result.error("请输入头程起飞日期");
            }
            if (flightDateTime == null || flightDateTime.trim().isEmpty()) {
                return Result.error("请输入头程起飞时间");
            }
            
            // 获取用户ID
            Long userIdLong = (Long) request.getAttribute("userId");
            Integer userId = userIdLong != null ? userIdLong.intValue() : null;
            String username = (String) request.getAttribute("username");
            
            boolean result = orderService.batchFirstFlightTakeoff(orderIds, flightDate, flightDateTime, remarks, userId);
            if (result) {
                // 记录操作日志
                if (userIdLong != null && username != null) {
                    for (Long id : orderIds) {
                        logUtil.logAction(userIdLong, username, "order_list", id, "批量联程头程起飞:" + flightDate + " " + flightDateTime, request);
                    }
                }
                return Result.success("批量联程头程起飞成功", true);
            }
            return Result.error("批量联程头程起飞失败");
        } catch (Exception e) {
            log.error("批量联程头程起飞失败", e);
            return Result.error("批量联程头程起飞失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据提单号修改提单号
     */
    @RequiresPermission("edit")
    @PostMapping("/reset-bl-no-by-bl-no")
    public Result<Boolean> resetBlNoByBlNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String oldBlNo = (String) params.get("oldBlNo");
            String newBlNo = (String) params.get("newBlNo");
            
            if (oldBlNo == null || oldBlNo.trim().isEmpty()) {
                return Result.error("请输入旧提单号");
            }
            if (newBlNo == null || newBlNo.trim().isEmpty()) {
                return Result.error("请输入新提单号");
            }
            
            // 获取用户ID
            Long userIdLong = (Long) request.getAttribute("userId");
            Integer userId = userIdLong != null ? userIdLong.intValue() : null;
            String username = (String) request.getAttribute("username");
            
            boolean result = orderService.resetBlNoByBlNo(oldBlNo.trim(), newBlNo.trim(), userId);
            if (result) {
                // 记录操作日志
                if (userIdLong != null && username != null) {
                    logUtil.logAction(userIdLong, username, "bl_list", null, "根据提单号修改提单号:" + oldBlNo + "改为" + newBlNo, request);
                }
                return Result.success("根据提单号修改提单号成功", true);
            }
            return Result.error("根据提单号修改提单号失败");
        } catch (Exception e) {
            log.error("根据提单号修改提单号失败", e);
            return Result.error("根据提单号修改提单号失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据头程单号修改提单号
     */
    @RequiresPermission("edit")
    @PostMapping("/reset-bl-no-by-tx-no")
    public Result<Boolean> resetBlNoByTxNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String txNo = (String) params.get("txNo");
            String oldBlNo = (String) params.get("oldBlNo");
            String newBlNo = (String) params.get("newBlNo");
            
            if (txNo == null || txNo.trim().isEmpty()) {
                return Result.error("请输入头程单号");
            }
            if (oldBlNo == null || oldBlNo.trim().isEmpty()) {
                return Result.error("请输入旧提单号");
            }
            if (newBlNo == null || newBlNo.trim().isEmpty()) {
                return Result.error("请输入新提单号");
            }
            
            // 获取用户ID
            Long userIdLong = (Long) request.getAttribute("userId");
            Integer userId = userIdLong != null ? userIdLong.intValue() : null;
            String username = (String) request.getAttribute("username");
            
            boolean result = orderService.resetBlNoByTxNo(txNo.trim(), oldBlNo.trim(), newBlNo.trim(), userId);
            if (result) {
                // 记录操作日志（PHP逻辑：为每个ship_log和order_list都记录日志）
                // 注意：由于需要在Service层获取ship_log列表，这里暂时只记录一条日志
                // 如果需要完全一致，需要在Service层返回ship_log列表，然后在这里循环记录
                if (userIdLong != null && username != null) {
                    logUtil.logAction(userIdLong, username, "ship_log", null, "根据头程单号修改提单号:" + oldBlNo + "改为" + newBlNo, request);
                }
                return Result.success("根据头程单号修改提单号成功", true);
            }
            return Result.error("根据头程单号修改提单号失败");
        } catch (Exception e) {
            log.error("根据头程单号修改提单号失败", e);
            return Result.error("根据头程单号修改提单号失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号修改提单号
     */
    @RequiresPermission("edit")
    @PostMapping("/reset-bl-no-by-order-no")
    public Result<Boolean> resetBlNoByOrderNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            String oldBlNo = (String) params.get("oldBlNo");
            String newBlNo = (String) params.get("newBlNo");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("请输入订单号");
            }
            if (oldBlNo == null || oldBlNo.trim().isEmpty()) {
                return Result.error("请输入旧提单号");
            }
            if (newBlNo == null || newBlNo.trim().isEmpty()) {
                return Result.error("请输入新提单号");
            }
            
            // 获取用户ID
            Long userIdLong = (Long) request.getAttribute("userId");
            Integer userId = userIdLong != null ? userIdLong.intValue() : null;
            String username = (String) request.getAttribute("username");
            
            boolean result = orderService.resetBlNoByOrderNo(orderNo.trim(), oldBlNo.trim(), newBlNo.trim(), userId);
            if (result) {
                // 记录操作日志
                if (userIdLong != null && username != null) {
                    // 查询订单ID用于日志记录
                    com.adk.backend.entity.LxOrderList order = orderService.getOrderByNo(orderNo.trim());
                    Long orderId = order != null ? order.getId() : null;
                    logUtil.logAction(userIdLong, username, "order_list", orderId, "根据订单号修改提单号:" + oldBlNo + "改为" + newBlNo, request);
                }
                return Result.success("根据订单号修改提单号成功", true);
            }
            return Result.error("根据订单号修改提单号失败");
        } catch (Exception e) {
            log.error("根据订单号修改提单号失败", e);
            return Result.error("根据订单号修改提单号失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成授权码
     */
    @PostMapping("/generate-auth-code")
    @RequiresPermission("generate_auth_code")
    public Result<Map<String, Object>> generateAuthCode(HttpServletRequest request) {
        try {
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            Map<String, Object> result = orderService.generateAuthCode(userId);
            Integer code = (Integer) result.get("code");
            if (code != null && code == 1) {
                return Result.success((String) result.get("msg"), result);
            } else {
                return Result.error((String) result.get("msg"));
            }
        } catch (Exception e) {
            log.error("生成授权码失败", e);
            return Result.error("生成授权码失败：" + e.getMessage());
        }
    }
    
    /**
     * 重置头程日期（根据头程单号）
     */
    @PostMapping("/reset-tx-date")
    @RequiresPermission("reset_tx_date")
    public Result<String> resetTxDate(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String txNo = (String) params.get("txNo");
            String txDate = (String) params.get("txDate");
            String txDateTime = (String) params.get("txDateTime");
            
            if (txNo == null || txNo.trim().isEmpty() || txDate == null || txDate.trim().isEmpty() || 
                txDateTime == null || txDateTime.trim().isEmpty()) {
                return Result.error("参数不完整");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetTxDate(txNo.trim(), txDate.trim(), txDateTime.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "ship_log", null, "超级操作,重置头程日期: " + txNo, request);
                return Result.success("已重置");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("重置头程日期失败", e);
            return Result.error("重置头程日期失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据提单号重置头程日期
     */
    @PostMapping("/reset-tx-date-by-bl-no")
    @RequiresPermission("reset_tx_date_by_bl_no")
    public Result<String> resetTxDateByBlNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String blNo = (String) params.get("blNo");
            String txDate = (String) params.get("txDate");
            String txDateTime = (String) params.get("txDateTime");
            
            if (blNo == null || blNo.trim().isEmpty() || txDate == null || txDate.trim().isEmpty() || 
                txDateTime == null || txDateTime.trim().isEmpty()) {
                return Result.error("参数不完整");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetTxDateByBlNo(blNo.trim(), txDate.trim(), txDateTime.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "ship_log", null, "超级操作,根据提单号重置头程日期: " + blNo, request);
                return Result.success("已重置");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("根据提单号重置头程日期失败", e);
            return Result.error("根据提单号重置头程日期失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据提单号重置航班起飞日期
     */
    @PostMapping("/reset-flight-date-by-bl-no")
    @RequiresPermission("reset_flight_date_by_bl_no")
    public Result<String> resetFlightDateByBlNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String blNo = (String) params.get("blNo");
            String flightDate = (String) params.get("flightDate");
            String flightDateTime = (String) params.get("flightDateTime");
            
            if (blNo == null || blNo.trim().isEmpty() || flightDate == null || flightDate.trim().isEmpty() || 
                flightDateTime == null || flightDateTime.trim().isEmpty()) {
                return Result.error("参数不完整");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetFlightDateByBlNo(blNo.trim(), flightDate.trim(), flightDateTime.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "ship_log", null, "超级操作,根据提单号重置航班日期: " + blNo, request);
                return Result.success("已重置");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("根据提单号重置航班起飞日期失败", e);
            return Result.error("根据提单号重置航班起飞日期失败：" + e.getMessage());
        }
    }
    
    /**
     * 清除头程单号（根据订单号）
     */
    @PostMapping("/remove-tx-no")
    @RequiresPermission("remove_tx_no")
    public Result<String> removeTxNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.removeTxNo(orderNo.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "超级操作,根据订单号清除头程号: " + orderNo, request);
                return Result.success("已清除");
            } else {
                return Result.error("清除失败");
            }
        } catch (Exception e) {
            log.error("清除头程单号失败", e);
            return Result.error("清除头程单号失败：" + e.getMessage());
        }
    }
    
    /**
     * 重置发货数（根据订单号）
     */
    @PostMapping("/reset-shipped-qty")
    @RequiresPermission("reset_shipped_qty")
    public Result<String> resetShippedQty(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            Object shippedQtyObj = params.get("shippedQty");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            Integer shippedQty = null;
            if (shippedQtyObj instanceof Integer) {
                shippedQty = (Integer) shippedQtyObj;
            } else if (shippedQtyObj instanceof Number) {
                shippedQty = ((Number) shippedQtyObj).intValue();
            } else if (shippedQtyObj != null) {
                shippedQty = Integer.parseInt(shippedQtyObj.toString());
            }
            
            if (shippedQty == null || shippedQty < 0) {
                shippedQty = 0;
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetShippedQty(orderNo.trim(), shippedQty, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "修改子订单发货数: " + orderNo + ", 发货数: " + shippedQty, request);
                return Result.success("Success");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("重置发货数失败", e);
            return Result.error("重置发货数失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号重置出库日期
     */
    @PostMapping("/reset-ob-time")
    @RequiresPermission("reset_ob_time")
    public Result<String> resetObTime(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            String statusDate = (String) params.get("statusDate");
            String statusDateTime = (String) params.get("statusDateTime");
            
            if (orderNo == null || orderNo.trim().isEmpty() || statusDate == null || statusDate.trim().isEmpty() || 
                statusDateTime == null || statusDateTime.trim().isEmpty()) {
                return Result.error("参数不完整");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetObTime(orderNo.trim(), statusDate.trim(), statusDateTime.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "修改订单出库日期: " + orderNo, request);
                return Result.success("Success");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("根据订单号重置出库日期失败", e);
            return Result.error("根据订单号重置出库日期失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号强行重置计费重
     */
    @PostMapping("/reset-ship-weight")
    @RequiresPermission("reset_ship_weight")
    public Result<String> resetShipWeight(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            Object shipWeightObj = params.get("shipWeight");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            if (shipWeightObj == null) {
                return Result.error("计费重不能为空");
            }
            
            java.math.BigDecimal shipWeight;
            if (shipWeightObj instanceof java.math.BigDecimal) {
                shipWeight = (java.math.BigDecimal) shipWeightObj;
            } else if (shipWeightObj instanceof Number) {
                shipWeight = java.math.BigDecimal.valueOf(((Number) shipWeightObj).doubleValue());
            } else {
                shipWeight = new java.math.BigDecimal(shipWeightObj.toString());
            }
            
            if (shipWeight.compareTo(java.math.BigDecimal.ZERO) < 0) {
                return Result.error("计费重不能为负数");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetShipWeight(orderNo.trim(), shipWeight, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "重置计费重为: " + shipWeight + ", 订单号: " + orderNo, request);
                return Result.success("计费重重置成功");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("根据订单号强行重置计费重失败", e);
            return Result.error("根据订单号强行重置计费重失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号重设业务
     */
    @PostMapping("/reset-yw-by-order-no")
    @RequiresPermission("reset_yw_by_order_no")
    public Result<String> resetYwByOrderNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            Object salesUidObj = params.get("salesUid");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            if (salesUidObj == null) {
                return Result.error("业务员ID不能为空");
            }
            
            Long salesUid = null;
            if (salesUidObj instanceof Long) {
                salesUid = (Long) salesUidObj;
            } else if (salesUidObj instanceof Number) {
                salesUid = ((Number) salesUidObj).longValue();
            } else {
                salesUid = Long.parseLong(salesUidObj.toString());
            }
            
            if (salesUid == null || salesUid <= 0) {
                return Result.error("业务员ID必须大于0");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetYwByOrderNo(orderNo.trim(), salesUid, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "重置订单业务,订单号: " + orderNo + ", 业务员ID: " + salesUid, request);
                return Result.success("已重设业务");
            } else {
                return Result.error("重设业务失败");
            }
        } catch (Exception e) {
            log.error("根据订单号重设业务失败", e);
            return Result.error("根据订单号重设业务失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号强行重置同行计费重
     */
    @PostMapping("/reset-tx-ship-weight")
    @RequiresPermission("reset_tx_ship_weight")
    public Result<String> resetTxShipWeight(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            Object txShipWeightObj = params.get("txShipWeight");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            if (txShipWeightObj == null) {
                return Result.error("同行计费重不能为空");
            }
            
            java.math.BigDecimal txShipWeight;
            if (txShipWeightObj instanceof java.math.BigDecimal) {
                txShipWeight = (java.math.BigDecimal) txShipWeightObj;
            } else if (txShipWeightObj instanceof Number) {
                txShipWeight = java.math.BigDecimal.valueOf(((Number) txShipWeightObj).doubleValue());
            } else {
                txShipWeight = new java.math.BigDecimal(txShipWeightObj.toString());
            }
            
            if (txShipWeight.compareTo(java.math.BigDecimal.ZERO) < 0) {
                return Result.error("同行计费重不能为负数");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetTxShipWeight(orderNo.trim(), txShipWeight, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "重置同行计费重为: " + txShipWeight + ", 订单号: " + orderNo, request);
                return Result.success("同行计费重重置成功");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("根据订单号强行重置同行计费重失败", e);
            return Result.error("根据订单号强行重置同行计费重失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号更改订单所属客户
     */
    @PostMapping("/reset-customer-id-by-order-no")
    @RequiresPermission("reset_customer_id_by_order_no")
    public Result<String> resetCustomerIdByOrderNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            Object newCustomerIdObj = params.get("newCustomerId");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            if (newCustomerIdObj == null) {
                return Result.error("客户ID不能为空");
            }
            
            Long newCustomerId = null;
            if (newCustomerIdObj instanceof Long) {
                newCustomerId = (Long) newCustomerIdObj;
            } else if (newCustomerIdObj instanceof Number) {
                newCustomerId = ((Number) newCustomerIdObj).longValue();
            } else {
                newCustomerId = Long.parseLong(newCustomerIdObj.toString());
            }
            
            if (newCustomerId == null || newCustomerId <= 0) {
                return Result.error("客户ID必须大于0");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetCustomerIdByOrderNo(orderNo.trim(), newCustomerId, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "原客户id修改为新ID: " + newCustomerId + ", 订单号: " + orderNo, request);
                return Result.success("修改成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("根据订单号更改订单所属客户失败", e);
            return Result.error("根据订单号更改订单所属客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号强行重置实际体积
     */
    @PostMapping("/reset-true-vw-by-order-no")
    @RequiresPermission("reset_true_vw_by_order_no")
    public Result<String> resetTrueVwByOrderNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            Object trueVwObj = params.get("trueVw");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            if (trueVwObj == null) {
                return Result.error("实际体积不能为空");
            }
            
            java.math.BigDecimal trueVw;
            if (trueVwObj instanceof java.math.BigDecimal) {
                trueVw = (java.math.BigDecimal) trueVwObj;
            } else if (trueVwObj instanceof Number) {
                trueVw = java.math.BigDecimal.valueOf(((Number) trueVwObj).doubleValue());
            } else {
                trueVw = new java.math.BigDecimal(trueVwObj.toString());
            }
            
            if (trueVw.compareTo(java.math.BigDecimal.ZERO) <= 0) {
                return Result.error("实际体积必须大于0");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetTrueVwByOrderNo(orderNo.trim(), trueVw, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "重置订单实际体积为: " + trueVw + ", 订单号: " + orderNo, request);
                return Result.success("强行重置实际体积操作成功");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("根据订单号强行重置实际体积失败", e);
            return Result.error("根据订单号强行重置实际体积失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据提单号修改提单重量
     */
    @PostMapping("/reset-gw-by-bl-no")
    @RequiresPermission("reset_gw_by_bl_no")
    public Result<String> resetGwByBlNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String blNo = (String) params.get("blNo");
            Object gwObj = params.get("gw");
            
            if (blNo == null || blNo.trim().isEmpty()) {
                return Result.error("提单号不能为空");
            }
            
            if (gwObj == null) {
                return Result.error("重量不能为空");
            }
            
            java.math.BigDecimal gw;
            if (gwObj instanceof java.math.BigDecimal) {
                gw = (java.math.BigDecimal) gwObj;
            } else if (gwObj instanceof Number) {
                gw = java.math.BigDecimal.valueOf(((Number) gwObj).doubleValue());
            } else {
                gw = new java.math.BigDecimal(gwObj.toString());
            }
            
            if (gw.compareTo(java.math.BigDecimal.ZERO) < 0) {
                return Result.error("重量不能为负数");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetGwByBlNo(blNo.trim(), gw, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "bl_list", null, "原提单重量修改为新重量: " + gw + ", 提单号: " + blNo, request);
                return Result.success("修改成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("根据提单号修改提单重量失败", e);
            return Result.error("根据提单号修改提单重量失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据头程单号修改头程单号
     */
    @PostMapping("/reset-tx-no-by-tx-no")
    @RequiresPermission("reset_tx_no_by_tx_no")
    public Result<String> resetTxNoByTxNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String txNo = (String) params.get("txNo");
            String newTxNo = (String) params.get("newTxNo");
            
            if (txNo == null || txNo.trim().isEmpty() || newTxNo == null || newTxNo.trim().isEmpty()) {
                return Result.error("参数不完整");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            // 先查询旧的头程单号对应的订单ID，用于记录日志
            QueryWrapper<LxShipLog> oldWrapper = new QueryWrapper<>();
            oldWrapper.eq("tx_no", txNo.trim());
            List<LxShipLog> oldShipLogs = shipLogMapper.selectList(oldWrapper);
            
            boolean success = orderService.resetTxNoByTxNo(txNo.trim(), newTxNo.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                // 记录操作日志
                for (LxShipLog shipLog : oldShipLogs) {
                    if (shipLog.getOlId() != null) {
                        logUtil.logAction(userIdLong, username != null ? username : "", "order_list", shipLog.getOlId(), "高级操作,根据头程单号修改头程单号,由: " + txNo + " 改为 " + newTxNo, request);
                    }
                }
                return Result.success("修改头程单号操作成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("根据头程单号修改头程单号失败", e);
            return Result.error("根据头程单号修改头程单号失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号修改运输方式
     */
    @PostMapping("/reset-order-ship-type")
    @RequiresPermission("reset_order_ship_type")
    public Result<String> resetOrderShipType(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            Object shipTypeObj = params.get("shipType");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            if (shipTypeObj == null) {
                return Result.error("运输方式不能为空");
            }
            
            Integer shipType = null;
            if (shipTypeObj instanceof Integer) {
                shipType = (Integer) shipTypeObj;
            } else if (shipTypeObj instanceof Number) {
                shipType = ((Number) shipTypeObj).intValue();
            } else {
                shipType = Integer.parseInt(shipTypeObj.toString());
            }
            
            if (shipType == null || shipType <= 0) {
                return Result.error("运输方式无效");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetOrderShipType(orderNo.trim(), shipType, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "根据订单号修改运输方式: " + orderNo + ", 运输方式: " + shipType, request);
                return Result.success("修改运输方式成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("根据订单号修改运输方式失败", e);
            return Result.error("根据订单号修改运输方式失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号修改订单号
     */
    @PostMapping("/reset-order-no-by-order-no")
    @RequiresPermission("reset_order_no_order_tx_no")
    public Result<String> resetOrderNoByOrderNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            String newOrderNo = (String) params.get("newOrderNo");
            
            if (orderNo == null || orderNo.trim().isEmpty() || newOrderNo == null || newOrderNo.trim().isEmpty()) {
                return Result.error("参数不完整");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetOrderNoByOrderNo(orderNo.trim(), newOrderNo.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "高级操作,根据订单号修改订单号,由: " + orderNo + " 改为 " + newOrderNo, request);
                return Result.success("修改订单号操作成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("根据订单号修改订单号失败", e);
            return Result.error("根据订单号修改订单号失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据提单号修改Manifest申报金额
     */
    @PostMapping("/reset-manifest-fee-by-bl-no")
    @RequiresPermission("reset_manifest_fee")
    public Result<String> resetManifestFeeByBlNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String blNo = (String) params.get("blNo");
            Object mainfestFeeObj = params.get("mainfestFee");
            
            if (blNo == null || blNo.trim().isEmpty()) {
                return Result.error("提单号不能为空");
            }
            
            if (mainfestFeeObj == null) {
                return Result.error("Manifest申报金额不能为空");
            }
            
            java.math.BigDecimal mainfestFee;
            if (mainfestFeeObj instanceof java.math.BigDecimal) {
                mainfestFee = (java.math.BigDecimal) mainfestFeeObj;
            } else if (mainfestFeeObj instanceof Number) {
                mainfestFee = java.math.BigDecimal.valueOf(((Number) mainfestFeeObj).doubleValue());
            } else {
                mainfestFee = new java.math.BigDecimal(mainfestFeeObj.toString());
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetManifestFeeByBlNo(blNo.trim(), mainfestFee, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "bl_list", null, "修改提单的MainFest费用,提单号: " + blNo + ", 金额: " + mainfestFee, request);
                return Result.success("Success");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("根据提单号修改Manifest申报金额失败", e);
            return Result.error("根据提单号修改Manifest申报金额失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据柜号强行修改海运费
     */
    @PostMapping("/reset-ship-fee-by-loading-no")
    @RequiresPermission("reset_ship_fee")
    public Result<String> resetShipFeeByLoadingNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String loadingNo = (String) params.get("loadingNo");
            Object shipFeeObj = params.get("shipFee");
            
            if (loadingNo == null || loadingNo.trim().isEmpty()) {
                return Result.error("柜号不能为空");
            }
            
            if (shipFeeObj == null) {
                return Result.error("海运费不能为空");
            }
            
            java.math.BigDecimal shipFee;
            if (shipFeeObj instanceof java.math.BigDecimal) {
                shipFee = (java.math.BigDecimal) shipFeeObj;
            } else if (shipFeeObj instanceof Number) {
                shipFee = java.math.BigDecimal.valueOf(((Number) shipFeeObj).doubleValue());
            } else {
                shipFee = new java.math.BigDecimal(shipFeeObj.toString());
            }
            
            if (shipFee.compareTo(java.math.BigDecimal.ZERO) <= 0) {
                return Result.error("海运费必须大于0");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetShipFeeByLoadingNo(loadingNo.trim(), shipFee, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "loading_details", null, "根据柜号强行修改海运费,柜号: " + loadingNo + ", 海运费: " + shipFee, request);
                return Result.success("Success");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("根据柜号强行修改海运费失败", e);
            return Result.error("根据柜号强行修改海运费失败：" + e.getMessage());
        }
    }
    
    /**
     * 重置为待入库
     */
    @PostMapping("/reset-pending-ib")
    @RequiresPermission("reset_pending_ib")
    public Result<String> resetPendingIb(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetPendingIb(orderNo.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "重置为待入库状态,订单号: " + orderNo, request);
                return Result.success("已重置为待入库");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("重置为待入库失败", e);
            return Result.error("重置为待入库失败：" + e.getMessage());
        }
    }
    
    /**
     * 重置为待确认计费重
     */
    @PostMapping("/reset-confirm-weight")
    @RequiresPermission("reset_confirm_weigth")
    public Result<String> resetConfirmWeight(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetConfirmWeight(orderNo.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "重置为计费重待确认,订单号: " + orderNo, request);
                return Result.success("已重置国内仓已收货");
            } else {
                return Result.error("操作失败,已出库订单不允许重置");
            }
        } catch (Exception e) {
            log.error("重置为待确认计费重失败", e);
            return Result.error("重置为待确认计费重失败：" + e.getMessage());
        }
    }
    
    /**
     * 重置为已确认计费重
     */
    @PostMapping("/reset-confirmed-weight")
    @RequiresPermission("reset_confirmed_weigth")
    public Result<String> resetConfirmedWeight(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetConfirmedWeight(orderNo.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "重置为计费重已确认,订单号: " + orderNo, request);
                return Result.success("已重置国内仓已收货");
            } else {
                return Result.error("重置失败");
            }
        } catch (Exception e) {
            log.error("重置为已确认计费重失败", e);
            return Result.error("重置为已确认计费重失败：" + e.getMessage());
        }
    }
    
    /**
     * 打开订单拆单权限
     */
    @PostMapping("/reset-create-xx")
    @RequiresPermission("reset_create_xx")
    public Result<String> resetCreateXx(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetCreateXx(orderNo.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "超级操作,打开拆单权限,订单号: " + orderNo, request);
                return Result.success("Success");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("打开订单拆单权限失败", e);
            return Result.error("打开订单拆单权限失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据提单号回退订单状态
     */
    @PostMapping("/reset-order-status-by-bl-no")
    @RequiresPermission("reset_order_status_by_bl_no")
    public Result<String> resetOrderStatusByBlNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String blNo = (String) params.get("blNo");
            Object customerStatusObj = params.get("customerStatus");
            
            if (blNo == null || blNo.trim().isEmpty()) {
                return Result.error("提单号不能为空");
            }
            
            if (customerStatusObj == null) {
                return Result.error("目标状态不能为空");
            }
            
            Integer customerStatus = null;
            if (customerStatusObj instanceof Integer) {
                customerStatus = (Integer) customerStatusObj;
            } else if (customerStatusObj instanceof Number) {
                customerStatus = ((Number) customerStatusObj).intValue();
            } else {
                customerStatus = Integer.parseInt(customerStatusObj.toString());
            }
            
            if (customerStatus == null || customerStatus <= 2) {
                return Result.error("目标状态无效（必须大于2）");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetOrderStatusByBlNo(blNo.trim(), customerStatus, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "根据提单号回退订单状态为: " + customerStatus + ", 提单号: " + blNo, request);
                return Result.success("已回退");
            } else {
                return Result.error("重置错误");
            }
        } catch (Exception e) {
            log.error("根据提单号回退订单状态失败", e);
            return Result.error("根据提单号回退订单状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单号回退订单状态
     */
    @PostMapping("/reset-order-status-by-order-no")
    @RequiresPermission("reset_order_status_by_order_no")
    public Result<String> resetOrderStatusByOrderNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            Object customerStatusObj = params.get("customerStatus");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            if (customerStatusObj == null) {
                return Result.error("目标状态不能为空");
            }
            
            Integer customerStatus = null;
            if (customerStatusObj instanceof Integer) {
                customerStatus = (Integer) customerStatusObj;
            } else if (customerStatusObj instanceof Number) {
                customerStatus = ((Number) customerStatusObj).intValue();
            } else {
                customerStatus = Integer.parseInt(customerStatusObj.toString());
            }
            
            if (customerStatus == null || customerStatus <= 0) {
                return Result.error("目标状态无效（必须大于0）");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetOrderStatusByOrderNo(orderNo.trim(), customerStatus, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "回退订单状态为: " + customerStatus + ", 订单号: " + orderNo, request);
                return Result.success("已回退");
            } else {
                return Result.error("重置错误");
            }
        } catch (Exception e) {
            log.error("根据订单号回退订单状态失败", e);
            return Result.error("根据订单号回退订单状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据头程单号回退订单状态
     */
    @PostMapping("/reset-order-status-by-tx-no")
    @RequiresPermission("reset_order_status_by_tx_no")
    public Result<String> resetOrderStatusByTxNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String txNo = (String) params.get("txNo");
            Object customerStatusObj = params.get("customerStatus");
            
            if (txNo == null || txNo.trim().isEmpty()) {
                return Result.error("头程单号不能为空");
            }
            
            if (customerStatusObj == null) {
                return Result.error("目标状态不能为空");
            }
            
            Integer customerStatus = null;
            if (customerStatusObj instanceof Integer) {
                customerStatus = (Integer) customerStatusObj;
            } else if (customerStatusObj instanceof Number) {
                customerStatus = ((Number) customerStatusObj).intValue();
            } else {
                customerStatus = Integer.parseInt(customerStatusObj.toString());
            }
            
            if (customerStatus == null || customerStatus <= 2) {
                return Result.error("目标状态无效（必须大于2）");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetOrderStatusByTxNo(txNo.trim(), customerStatus, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "根据头程单号回退订单状态为: " + customerStatus + ", 头程单号: " + txNo, request);
                return Result.success("已回退");
            } else {
                return Result.error("重置错误");
            }
        } catch (Exception e) {
            log.error("根据头程单号回退订单状态失败", e);
            return Result.error("根据头程单号回退订单状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据柜号回退订单状态
     */
    @PostMapping("/reset-order-status-by-loading-no")
    @RequiresPermission("reset_order_status_by_loading_no")
    public Result<String> resetOrderStatusByLoadingNo(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String loadingNo = (String) params.get("loadingNo");
            Object customerStatusObj = params.get("customerStatus");
            
            if (loadingNo == null || loadingNo.trim().isEmpty()) {
                return Result.error("柜号不能为空");
            }
            
            if (customerStatusObj == null) {
                return Result.error("目标状态不能为空");
            }
            
            Integer customerStatus = null;
            if (customerStatusObj instanceof Integer) {
                customerStatus = (Integer) customerStatusObj;
            } else if (customerStatusObj instanceof Number) {
                customerStatus = ((Number) customerStatusObj).intValue();
            } else {
                customerStatus = Integer.parseInt(customerStatusObj.toString());
            }
            
            if (customerStatus == null || customerStatus <= 2) {
                return Result.error("目标状态无效（必须大于2）");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.resetOrderStatusByLoadingNo(loadingNo.trim(), customerStatus, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "根据柜号回退订单状态为: " + customerStatus + ", 柜号: " + loadingNo, request);
                return Result.success("已回退");
            } else {
                return Result.error("重置错误");
            }
        } catch (Exception e) {
            log.error("根据柜号回退订单状态失败", e);
            return Result.error("根据柜号回退订单状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 超级删除订单
     */
    @PostMapping("/supper-del")
    @RequiresPermission("supper_del")
    public Result<String> supperDel(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            Object authCodeObj = params.get("authCode");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            Integer authCode = null;
            if (authCodeObj != null) {
                if (authCodeObj instanceof Integer) {
                    authCode = (Integer) authCodeObj;
                } else if (authCodeObj instanceof Number) {
                    authCode = ((Number) authCodeObj).intValue();
                } else {
                    try {
                        authCode = Integer.parseInt(authCodeObj.toString());
                    } catch (NumberFormatException e) {
                        // 忽略无效的授权码
                    }
                }
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.supperDel(orderNo.trim(), authCode, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "超级删除订单: " + orderNo, request);
                return Result.success("删掉了");
            } else {
                return Result.error("已发货订单无法删除");
            }
        } catch (Exception e) {
            log.error("超级删除订单失败", e);
            return Result.error("超级删除订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 超级删除子订单
     */
    @PostMapping("/supper-del-sub-order")
    @RequiresPermission("supper_del_sub_order")
    public Result<String> supperDelSubOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String orderNo = (String) params.get("orderNo");
            
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.supperDelSubOrder(orderNo.trim(), userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "ship_log", null, "超级删除子订单: " + orderNo, request);
                return Result.success("删掉了");
            } else {
                return Result.error("已发货订单无法删除");
            }
        } catch (Exception e) {
            log.error("超级删除子订单失败", e);
            return Result.error("超级删除子订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 上传仓库收货数据
     */
    @PostMapping("/update-recv-logs")
    @RequiresPermission("update_recv_logs")
    public Result<String> updateRecvLogs(
            @RequestParam("orderNo") String orderNo,
            @RequestParam("excelFile") org.springframework.web.multipart.MultipartFile excelFile,
            HttpServletRequest request) {
        try {
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            if (excelFile == null || excelFile.isEmpty()) {
                return Result.error("Excel文件不能为空");
            }
            
            Long userIdLong = (Long) request.getAttribute("userId");
            if (userIdLong == null) {
                return Result.error("用户未登录");
            }
            Integer userId = userIdLong.intValue();
            
            boolean success = orderService.updateRecvLogs(orderNo.trim(), excelFile, userId);
            if (success) {
                String username = (String) request.getAttribute("username");
                logUtil.logAction(userIdLong, username != null ? username : "", "order_list", null, "重置仓库收货数据,订单号: " + orderNo, request);
                return Result.success("仓库收货数据重置成功");
            } else {
                return Result.error("上传失败，请检查订单状态和Excel格式");
            }
        } catch (Exception e) {
            log.error("上传仓库收货数据失败", e);
            return Result.error("上传仓库收货数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 按月批量下载订单数据
     */
    @PostMapping("/supper-download")
    @RequiresPermission("supper_download")
    public void supperDownload(
            @RequestParam("startMonth") String startMonth,
            @RequestParam(required = false, defaultValue = "1") Integer downloadFrom,
            @RequestParam(required = false) Long customerId,
            HttpServletResponse response) {
        try {
            // 查询数据
            List<Map<String, Object>> data = orderService.supperDownload(startMonth, downloadFrom, customerId);
            
            // 准备表头（按照PHP代码的顺序）
            String[] headers = {
                "入库日期", "交货方式", "客户", "入仓号", "送仓类型", "备注", "报关", 
                "箱数", "计费重", "箱/票", "头程单号", "出库日期", "提单号", "最新动态", 
                "时间", "预约状态", "预约时间"
            };
            
            // 转换数据格式，将字段名映射到表头
            List<Map<String, Object>> exportData = new ArrayList<>();
            for (Map<String, Object> item : data) {
                Map<String, Object> row = new HashMap<>();
                row.put("入库日期", item.get("recv_time") != null ? item.get("recv_time") : "");
                row.put("交货方式", item.get("order_type") != null ? item.get("order_type") : "");
                row.put("客户", item.get("cus_code") != null ? item.get("cus_code") : "");
                row.put("入仓号", item.get("order_no") != null ? item.get("order_no") : "");
                row.put("送仓类型", item.get("des_add") != null ? item.get("des_add") : "");
                row.put("备注", item.get("remarks") != null ? item.get("remarks") : "");
                row.put("报关", item.get("declare_type") != null ? item.get("declare_type") : "");
                row.put("箱数", item.get("total_ctns") != null ? item.get("total_ctns") : "");
                row.put("计费重", item.get("ship_weigth") != null ? item.get("ship_weigth") : "");
                row.put("箱/票", item.get("shipped_qty") != null ? item.get("shipped_qty") : "");
                row.put("头程单号", item.get("tx_no") != null ? item.get("tx_no") : "");
                row.put("出库日期", item.get("tx_date") != null ? item.get("tx_date") : "");
                row.put("提单号", item.get("bl_no") != null ? item.get("bl_no") : "");
                row.put("最新动态", item.get("new_status") != null ? item.get("new_status") : "");
                row.put("时间", item.get("last_status_time") != null ? item.get("last_status_time") : "");
                row.put("预约状态", item.get("booking_status") != null ? item.get("booking_status") : "");
                row.put("预约时间", item.get("booking_date") != null ? item.get("booking_date") : "");
                exportData.add(row);
            }
            
            // 生成文件名
            String fileName = "Order_List_" + startMonth;
            if (downloadFrom != null && downloadFrom == 2) {
                fileName += "_By入库日期";
            } else {
                fileName += "_By出库日期";
            }
            
            // 导出Excel
            excelUtil.exportExcel(response, fileName, headers, exportData);
        } catch (Exception e) {
            log.error("按月批量下载失败", e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "按月批量下载失败：" + e.getMessage());
            } catch (IOException ioException) {
                log.error("发送错误响应失败", ioException);
            }
        }
    }
}

